简体   繁体   中英

C: fgets always NULL

I'm playing with file I/O in C.. I'm trying to use fgets to read data in from one file and output it to another file. The problem is that it always returns NULL and so nothing gets copied to the output file. Here's my code:

#include <stdio.h>
#include <stdlib.h>

int main()
{
    FILE *fpIn;
    FILE *fpOut;

    if ((fpIn = fopen("C:\\testIn.txt", "r") == NULL))
    {
        printf("Cannot open input file!\n");
        exit(1);
    }

    if ((fpOut = fopen("C:\\testOut.txt", "a") == NULL))
    {
        printf("Cannot open output file!\n");
        exit(1);
    }

    char buffer[128];
    while (fgets(buffer, 128, fpIn) != NULL)
    {
        fputs(buffer, fpOut);
    }

    fclose(fpIn);
    fclose(fpOut);

    system("PAUSE");
    return 0;
}

another thing; when I tried using "a+f" in the second arg for fopen, it didn't work.

if ((fpOut = fopen("C:\\testOut.txt", "a") == NULL))

Should be

if ((fpOut = fopen("C:\\testOut.txt", "a")) == NULL)

Same on the input file. If you are new to C, I'd suggest do one thing at a time to make it easier to track down issues. eg

fpOut = fopen("C:\\testOut.txt", "a");
if(fpOut == NULL) {
    ...

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM