Trouble reading a line using fscanf()

后端 未结 7 741
暖寄归人
暖寄归人 2020-12-01 15:40

I\'m trying to read a line using the following code:

while(fscanf(f, \"%[^\\n\\r]s\", cLine) != EOF )
{
    /* do something with cLine */
}

7条回答
  •  渐次进展
    2020-12-01 16:00

    If you want read a file line by line (Here, line separator == '\n') just make that:

    #include 
    #include 
    #include 
    
    int main(int argc, char **argv)
    {
            FILE *fp;
            char *buffer;
            int ret;
    
            // Open a file ("test.txt")
            if ((fp = fopen("test.txt", "r")) == NULL) {
                    fprintf(stdout, "Error: Can't open file !\n");
                    return -1;
            }
            // Alloc buffer size (Set your max line size)
            buffer = malloc(sizeof(char) * 4096);
            while(!feof(fp))
            {
                    // Clean buffer
                    memset(buffer, 0, 4096);
                    // Read a line
                    ret = fscanf(fp, "%4095[^\n]\n", buffer);
                    if (ret != EOF) {
                            // Print line
                            fprintf(stdout, "%s\n", buffer);
                    }
            }
            // Free buffer
            free(buffer);
            // Close file
            fclose(fp);
            return 0;
    }
    

    Enjoy :)

提交回复
热议问题