在iOS上用std编写文件
Writing files with std on iOS
我在xCode中向我的iPhone资源添加了一个save.txt,带有相同的文本"…"
我在文件中写了一些字符串,然后读了它,但当我读它时,我只得到旧的内容。。所以中没有任何新内容
NSString* resources = [ [ NSBundle mainBundle ] resourcePath ] ;
std::string respath( [ resources UTF8String ] ) ;
std::string fpath = respath + "/" + "save.txt" ;
std::ofstream file;
file.open(fpath.c_str(), std::ios::out );
file << "some textn";
file.close();
std::ifstream rf;
rf.open(fpath.c_str(), std::ios::in );
char str[255];
while(rf) {
rf.getline(str, 255);
if(rf) printf("%s", str);
}
您不能在应用程序包中写入或修改文件,file.open()调用肯定会失败,但您没有检查错误。相反,您应该写入应用程序的Documents文件夹。
根据您的代码示例,这将是:
NSArray *searchPaths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,
NSUserDomainMask, YES);
NSString *documentsPath = [searchPaths objectAtIndex:0];
std::string respath( [ documentsPath UTF8String ] ) ;
您在编写时从不检查错误。事实上,您没有写入该文件,如果检查了错误代码,可能会告诉您比我的答案更多的错误。
相关文章:
- 多个文件的内存分配错误"在抛出 'std :: bad_alloc' what (): std :: bad_alloc 的实例后终止调用" [C++]
- 如何传递多个 std::文件系统选项?
- 遍历顺序由 std::文件系统directory_iterator给出
- 使 std::fstream 写入文件末尾,但从头开始读取
- 是否可以使用 Python csv 阅读器读取使用 C++ std::setw 生成的文件?
- std::ifstream 在读取文件中最后一项时设置 eofbit,但仅在读取数值类型时发生
- C++:std::ofstream 方法 open() 在第二次迭代时擦除打开的 ifstream 文件
- 'std::wstring_convert'尽可能多地转换(从 UTF8 文件读取块)
- C++ VS 错误:<实验/文件系统>提供 std::experimental::文件系统的标头已被Microsoft弃用,将被删除
- 'generate'不是窗口头文件中'std::random_device'的成员<random>
- Windows std::fstream 修改文件后打开()?
- 是否可以使用 std::文件系统获取根名称列表?
- 如何将文件的一部分读取到std::list缓冲区?
- llvm 9在10.15之前的mac版本上支持std::文件系统吗
- 从带有 std::ifstream::read() 的文件中读取 int 遍历 char * 二进制数据
- 当 ofstream 指针位于 std::map 中时,文件写入不会发生 C++.
- std(boost)::文件系统::p ath 组件数
- 变量 std::fstream 文件具有初始值设定项,但类型不完整 编译错误
- std::文件系统根路径如何将自身作为父路径?
- 为什么我打开一个没有std::ios::binary的文件(std::ifstream)