1

What I want to do is write a method that when called will create a plain text file with a pre-written header (always the same) and then periodically updates the text file with more data until the user requests it to stop. A new text file would be needed for each different time the user uses the app.

I'm having difficulty even getting the app to create the text file in the first place. Any suggestions what I may need to do to accomplish this?

Thanks.

user3871995
  • 983
  • 1
  • 10
  • 19
  • 1
    Have a look at [http://stackoverflow.com/questions/16872261/how-to-create-a-new-text-file-to-write-to-in-objective-c-ipad-app](How to create a new text file to write to in objective c ipad app (Stackoverflow)) – PattaFeuFeu Jul 24 '14 at 08:32
  • I find the Cocoa APIs to do this quite difficult to use, so I would revert to using plain ol' C methods (`fopen()`, `fwrite()`, `fprintf()`, etc.) and keeping a `FILE *` instance variable. There should be tons of examples of how to do it in C, which will be easy to translate into Objective-C. – trojanfoe Jul 24 '14 at 08:35

1 Answers1

1

Have a look on following code, it creates a CSV file. Which is exactly what you require. If file doesn't exist it creates a new one and write headers first, otherwise just write the log text.

- (void)log:(NSString *)msg {

    NSString *fileName = [self logFilePath];

    // if new file the add headers
    FILE *file = fopen([fileName UTF8String], "r");
    if (file == NULL) {
        file = fopen([fileName UTF8String], "at");
        fprintf(file, "%s\n", "Date, Time, Latitude, Longitude, Speed, info");
    } else {
        fclose(file);
        file = fopen([fileName UTF8String], "at");
    }
    fprintf(file, "%s\n", [msg UTF8String]);
    fclose(file);
}

You should create your files in document directory, following code shows how to get path to the document directory

NSString *path = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject];
Zee
  • 1,865
  • 21
  • 42
  • Why the multiple `fopen()` calls? Using mode `"a+"` would do what you want and mode flag `t` is not even supported under UNIX platforms. Hint: use `ftell()` to see if the file is currently empty and the header needs to be written. – trojanfoe Jul 24 '14 at 09:15
  • That does look like the sort of thing I need to use. But if I'm calling that method to both create the file initially and then for periodically updating it, how can I get a unique file the next time the user uses the app? I'm not sure how to use the directories either – user3871995 Jul 24 '14 at 10:03