Android NDK C++ 讀寫文件

一、本地寫文件

方式一:

#include <fstream>
#include <iostream>

string info = "本地寫文件測試";
std::ofstream OsWrite("/sdcard/123.txt",std::ofstream::app);
OsWrite<<info;
OsWrite<<std::endl;
OsWrite.close();

方式二:

#include "unistd.h"
#include <fcntl.h>

const char *path = "/sdcard/123.txt"; // 路徑
const char *sState = "00000012345"; // 狀態
int fd = open(path, O_WRONLY);
if (fd < 0) {
    LOGE("PathPathPath  fail in open file %s", path);
    return;
}
write(fd, sState, strlen(sState));
close(fd);

二、讀本地文件內容

#include "unistd.h"
#include <fcntl.h>

string sState = "0";
const char *cPath = "/sdcard/123.txt"; //路徑
int fd = open(cPath, O_RDONLY);
if (fd < 0) {
    LOGE("Path  fail in open file %s", cPath);
    sState = "-1";
}
char data[11];
int len = read(fd, data, 10);
close(fd);
if (len > 0) {
    TrimSpace(data);
    sState = string(data);
} else {
    LOGE("Path fail in read file %s", cPath);
    sState = "-1";
}

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章