xcode 如何在IOS中写入文件
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/11666690/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to write a file in IOS
提问by Feroz
I am new to IOS programming. I want to write some data into file. I have opened successfully the file in Document path. But fwrite its not working as expected. If I open the file its empty. Its my code I'm using. What I'm doing wrong.
我是 IOS 编程的新手。我想将一些数据写入文件。我已成功打开文档路径中的文件。但是 fwrite 它没有按预期工作。如果我打开文件它是空的。它是我正在使用的代码。我做错了什么。
typedef struct test {
int a;
} TEST_OBJ;
TEST_OBJ test_obj1;
test_obj1.a = 5;
TEST_OBJ *data_ptr = &test_obj1;
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *appFile = [documentsDirectory stringByAppendingPathComponent:@"MyFile1.txt"];
//This is working fine.
// [data writeToFile:appFile atomically:YES];
NSFileManager *fileManager = [[NSFileManager alloc]init];
char const *path = [fileManager fileSystemRepresentationWithPath:appFile];
FILE *fp = fopen(path, "w+b");
// This write is not working. File is empty.
int cnt = fwrite (data_ptr , 1 , sizeof(test_obj1) , fp );
fclose(fp);
fp = NULL;
Anyone pls tell me what I'm doing wrong?
任何人请告诉我我做错了什么?
采纳答案by Feroz
I have changed the mode of opening a+ its writing and reading properly now. Thanks all for your help.
我已经改变了打开 a+ 的模式,现在可以正确地写和读了。感谢你的帮助。
回答by DrummerB
回答by cloosen
you can use NSData,NSArray,NSDictionary,they have [writeToFile: atomically:] method ,it can write the data into the file.
你可以使用 NSData、NSArray、NSDictionary,它们有 [writeToFile: atomically:] 方法,它可以将数据写入文件。
if you must C to read and write filestream,you can use my method below , it can add arrayString to the file .
如果你必须用 C 来读写文件流,你可以使用我下面的方法,它可以将 arrayString 添加到文件中。
- (void)putArrayString:(NSString *)arrayString toFilePath:(NSString *)filePath
{
FILE *fileStream = fopen([filePath UTF8String], "a+");
if(fileStream == NULL)
{
fclose(fileStream);
fileStream = fopen([filePath UTF8String], "w+");
fputs([arrayString UTF8String], fileStream);
}
else
{
fputs([arrayString UTF8String], fileStream);
}
fclose(fileStream);
}
回答by Khurram Ali
See if you can use this code:
看看你是否可以使用这个代码:
https://github.com/RIKSOF/three20/blob/master/src/extThree20RemoteObject/Source/TTObjectModel.m
https://github.com/RIKSOF/three20/blob/master/src/extThree20RemoteObject/Source/TTObjectModel.m
Start reading from the encodeToDocument method. It writes all properties of an object in to a JSON or XML file.
从 encodeToDocument 方法开始读取。它将对象的所有属性写入 JSON 或 XML 文件。
Any subclass of this class having any property is properly written back.
具有任何属性的此类的任何子类都被正确写回。