简体   繁体   中英

How to write a file in IOS

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.

 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?

I recommend you use NSData instead of C functions.

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

you can use NSData,NSArray,NSDictionary,they have [writeToFile: atomically:] method ,it can write the data into the file.

if you must C to read and write filestream,you can use my method below , it can add arrayString to the file .

- (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);
}

See if you can use this code:

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.

Any subclass of this class having any property is properly written back.

I have changed the mode of opening a+ its writing and reading properly now. Thanks all for your help.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM