Search code examples
iosxcodefile-read

File loop: read file into NSString, thats id is the filename ( without .txt)


I have a loop, that gets all files at a dir. Now I want to read every single file, each into a var, thats identifier is the filename without ending.

for example:

filename is text.txt now read content into NSString *"text" .

Here is my code example: Can someone help?

// create loop to read all files:
NSFileManager* fileManager = [[NSFileManager alloc] init];
fileManager = [[NSFileManager alloc] init];

NSDirectoryEnumerator* en = [fileManager enumeratorAtPath:directoryTMP];

NSString* file;
while (file = [en nextObject])
{
   NSLog(@"File To Read : %@",file);

   if([file isEqualToString:@"do_not_read_this.txt"])
   {
     NSLog(@"Skip this file for reading");
   }
else
   {
   // read file here:
   NSString *fileNameToRead = [NSString stringWithFormat:@"%@/%@.txt",directoryTMPeJL,file];

   NSString *fileNameWithoutEnd = [file stringByReplacingOccurrencesOfString:@".txt" withString: @""];

   // Read data from Dir
   NSString *<fileNameWithoutEnd> = [[NSString alloc] initWithContentsOfFile:fileNameToRead
                                                                            usedEncoding:nil
                                                                                   error:nil];
   }
}  

Solution

  • Well you cannot create named variables at runtime, but you could read the files into a NSMutableDictionary where the key is the filename (without the extension) and the value (object) is the file data:

    // create loop to read all files:
    NSMutableDictionary *files = [NSMutableDictionary new];
    NSFileManager* fileManager = [[NSFileManager alloc] init];
    fileManager = [[NSFileManager alloc] init];
    
    NSDirectoryEnumerator* en = [fileManager enumeratorAtPath:directoryTMP];
    
    NSString* file;
    while (file = [en nextObject])
    {
       NSLog(@"File To Read : %@",file);
    
       if([file isEqualToString:@"do_not_read_this.txt"])
       {
         NSLog(@"Skip this file for reading");
       }
       else
       {
           // read file here:
           NSString *fileNameToRead = [NSString stringWithFormat:@"%@/%@.txt",directoryTMPeJL,file];
    
           NSString *fileNameWithoutEnd = [file stringByReplacingOccurrencesOfString:@".txt" withString: @""];
    
           // Read data from Dir
           NSError *error = nil;
           NSString *data = [[NSString alloc] initWithContentsOfFile:fileNameToRead
                                                            encoding:NSUTF8StringEncoding
                                                               error:&error];
          if (data) {
              files[fileNameWithoutEnd] = data;
          } else {
              NSLog(@"Failed to read file '%@': %@", fileNameToRead, [error localizedDescription]);
          }
       }
    }