Getting words from text file to an array

前端 未结 3 2080
既然无缘
既然无缘 2021-01-14 12:43

My text file is formated like that:

my.txt
Red
Green
Blue
Yellow

I\'m tring to get words like that:

typedef char * string;
         


        
3条回答
  •  予麋鹿
    予麋鹿 (楼主)
    2021-01-14 13:03

    You'll need to allocate memory for your null-terminated strings.

    At the moment you are only allocating memory for 4 char *, but these pointers are uninitialized and therefor will result in UB (undefined behavior) when you try to write data to the memory pointed to by them.


    Working example snippet

    The use of "%127s" in the below snippet is to prevent us writing outside the bounds of the allocated memory. With the format-string in question we will at the most read/write 127 bytes + the null-terminator.

    Please remember that further error checks should be implemented if this is to be used in "real life".

    • Check to see that file_handle is indeed valid after attempt to open the file
    • Check to see that malloc did indeed allocate requested memory
    • Check to see that fscanf read the desired input

    #include 
    #include 
    #include 
    
    int
    main (int argc, char *argv[])
    {
      int i;
      char * lines[4];
      FILE *file_handle = fopen ("my.txt", "r");
    
      for (i =0; i < 4; ++i) {
        lines[i] = malloc (128); /* allocate a memory slot of 128 chars */
        fscanf (file_handle, "%127s", lines[i]);
      }
    
      for (i =0; i < 4; ++i)
        printf ("%d: %s\n", i, lines[i]);
    
      for (i =0; i < 4; ++i)
        free (lines[i]); /* remember to deallocated the memory allocated */
    
      return 0;
    }
    

    output

    0: Red
    1: Green
    2: Blue
    3: Yellow
    

提交回复
热议问题