Read string from file in C

后端 未结 3 531
春和景丽
春和景丽 2020-12-19 19:21

I have a file with multiple strings, each string on a separate line. All strings are 32 character long (so 33 with the \'\\n\' at the end).

I am trying to read all t

相关标签:
3条回答
  • 2020-12-19 19:36

    Here is a basic approach:

    // create an line array of length 33 (32 characters plus space for the terminating \0)
    char line[33];
    // read the lines from the file
    while (!feof(fp)) {
        // put the first 32 characters of the line into 'line'
        fgets(line, 32, fp);
        // put a '\0' at the end to terminate the string
        line[32] = '\0';
        // print the result
        printf("%s\n", line);
    }
    
    0 讨论(0)
  • 2020-12-19 19:42

    You code isn't working because you are only allocating space for lines of 30 characters plus a newline and a null terminator, and because you are only printing out one line after feof() returns true.

    Additionally, feof() returns true only after you have tried and failed to read past the end of file. This means that while (!feof(fp)) is generally incorrect - you should simply read until the reading function fails - at that point you can use feof() / ferror() to distinguish between end-of-file and other types of failures (if you need to). So, you code could look like:

    char line[34];
    
    while (fgets(line, 34, fp) != NULL) {
        printf("%s", line);
    }
    

    If you wish to find the first '\n' character in line, and replace it with '\0', you can use strchr() from <string.h>:

    char *p;
    
    p = strchr(line, '\n');
    if (p != NULL)
        *p = '\0';
    
    0 讨论(0)
  • 2020-12-19 19:58

    It goes something like this:

    char str[33]; //Remember the NULL terminator
    while(!feof(fp)) {
      fgets(str, 33, fp);
      printf("%s\n",str);
    }
    
    0 讨论(0)
提交回复
热议问题