Search code examples
cfileloopsfor-loopfgets

Reading text file into an array in C


I want to parse a .txt file into a 1D array in C. I'm using the fgets function to read the contents of the file into the array("waveform" as the array into which the file contents are to be stored - defined as a "char"). The saved values need to be saved into a new array as integer values. I am not sure where I am going wrong. P.S: I am new to programming in C, please bear with me :) Please ignore the indexing issues, done due to pasting

int main(){
    int a, win[10];

    FILE *filename = fopen("testFile.txt","r");
    char waveform[10];

    if (filename == NULL)
    {
        printf("Error opening file.\n");
        exit(8);
    }

    for(int i =0;1;i++){
        if(fgets(waveform[i], 10, filename) == NULL);
        break;

                if(i < 10)
            {
           a = atoi(waveform[i]);
           win[i] = a;
            }
         }

    fclose(filename);

    return 0; 
}

Compiler errors - image embedded

Data in testFile.txt: 1 to 10 in a row vector.


Solution

  • You are on the right track. Here is my contribution on the topic:

    1. Open the file (fopen)
    2. Count number of lines (getc and rewind)
    3. Read all lines into array (getline)
    4. Free memory and close file (free and fclose)

    Code example:

    #include <stdlib.h>
    #include <stdio.h>
    
    int main(int argc, char *argv[])
    {
    
      // Open File
      const char fname[] = "testFile.txt";
    
      FILE *fp = fopen(fname, "r");
    
      if( !fp )
        goto error_open_file;
      printf("Opened file: %s\n", fname); 
    
      // Count Lines
      char cr;
      size_t lines = 0;
    
      while( cr != EOF ) {
        if ( cr == '\n' ) {
          lines++;
        }
        cr = getc(fp);
      }
      printf("Number of lines: %ld\n", lines); 
      rewind(fp);
    
      // Read data
      {// 'goto' + data[lines] causes error, introduce block as a workaround
        char *data[lines];
        size_t n;
    
        for (size_t i = 0; i < lines; i++) {
          data[i] = NULL;
          size_t n = 0;
    
          getline(&data[i], &n, fp);
    
          if ( ferror( fp ) )
            goto error_read_file;
    
        }
    
        for (size_t i = 0; i < lines; i++) {
          printf("%s", data[i]);
          free(data[i]);
        }
      }
    
      // Close File
      fclose(fp);
    
      return 0;
    
    error_read_file:
      perror("fopen ");
      return 1;
    
    error_open_file:
      perror("getline ");
      return 2;
    
    }