gpt4 book ai didi

objective-c - 如何在IOS中写入文件

转载 作者:行者123 更新时间:2023-12-01 17:59:55 25 4
gpt4 key购买 nike

我是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;

有人告诉我我在做什么错吗?

最佳答案

我建议您使用 NSData 而不是C函数。

NSData *myData = [[NSData alloc] initWithBytes:bytes length:length];
[myData writeToFile:path atomically:YES];

关于objective-c - 如何在IOS中写入文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11666690/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com