C read file line by line

前端 未结 17 2181
后悔当初
后悔当初 2020-11-22 03:45

I wrote this function to read a line from a file:

const char *readLine(FILE *file) {

    if (file == NULL) {
        printf(\"Error: file pointer is null.\"         


        
17条回答
  •  广开言路
    2020-11-22 04:19

    A complete, fgets() solution:

    #include 
    #include 
    
    #define MAX_LEN 256
    
    int main(void)
    {
        FILE* fp;
        fp = fopen("file.txt", "r");
        if (fp == NULL) {
          perror("Failed: ");
          return 1;
        }
    
        char buffer[MAX_LEN];
        // -1 to allow room for NULL terminator for really long string
        while (fgets(buffer, MAX_LEN - 1, fp))
        {
            // Remove trailing newline
            buffer[strcspn(buffer, "\n")] = 0;
            printf("%s\n", buffer);
        }
    
        fclose(fp);
        return 0;
    }
    

    Output:

    First line of file
    Second line of file
    Third (and also last) line of file
    

    Remember, if you want to read from Standard Input (rather than a file as in this case), then all you have to do is pass stdin as the third parameter of fgets() method, like this:

    while(fgets(buffer, MAX_LEN - 1, stdin))
    

    Appendix

    Removing trailing newline character from fgets() input

    how to detect a file is opened or not in c

提交回复
热议问题