Jay_Ayres
Jay_Ayres

Reputation: 48

Troubles reading a txt file

I was having trouble to read a txt file in my app. I was able to write the file but i could not read the file i've just written. So i searched for some tutorials and decided to create a separated sample. But it still not working.

Here is the code i am using :

- (IBAction)gerarArquivo:(id)sender {
NSString *resultLine = [NSString stringWithFormat:@"%@,%@\n",@"teste1",@"teste2"];

NSString *docPath = [NSSearchPathForDirectoriesInDomains(NSDocumentationDirectory, NSUserDomainMask, YES)objectAtIndex:0];

NSString *surveys = [docPath stringByAppendingPathComponent:@"results.csv"];

if (![[NSFileManager defaultManager] fileExistsAtPath:surveys]) {
    [[NSFileManager defaultManager] createFileAtPath:surveys contents:nil attributes:nil];
}

NSFileHandle *fileHandle = [NSFileHandle fileHandleForUpdatingAtPath:surveys];
[fileHandle seekToEndOfFile];
[fileHandle writeData:[resultLine dataUsingEncoding:NSUTF8StringEncoding]];
[fileHandle closeFile];

NSLog(@"Foi");


}

- (IBAction)recuperarArquivo:(id)sender {

NSString *docPath = [NSSearchPathForDirectoriesInDomains(NSDocumentationDirectory, NSUserDomainMask, YES)objectAtIndex:0];

NSString *surveys = [docPath stringByAppendingPathComponent:@"results.csv"];

if ([[NSFileManager defaultManager] fileExistsAtPath:@"/results.csv"])
{
    NSFileHandle *fileHandle = [NSFileHandle fileHandleForReadingAtPath:surveys];

    NSString *surveyResults = [[NSString alloc]initWithData:[fileHandle availableData] encoding:NSUTF8StringEncoding];
    [fileHandle closeFile];
    NSLog(surveyResults);

}

}

Upvotes: 0

Views: 54

Answers (1)

Wain
Wain

Reputation: 119021

Your reading code has an if statement containing:

[[NSFileManager defaultManager] fileExistsAtPath:@"/results.csv"]

which is unlikely to work due to the supplied path (should be fileExistsAtPath:surveys), and if that doesn't work then you won't ever try to read the file contents.

Upvotes: 3

Related Questions