首页 > 解决方案 > f = fopen("textfile","a") 的代码在另一个设备中为 f 返回 NULL,但在我的设备上运行完美

问题描述

嗨,我已经在我的机器上创建并运行了一个程序,但是当我尝试在另一台机器上运行代码时它没有运行。

#include <stdio.h>
#include <stdlib.h>
int main()
{
    FILE *f;
    char buff[50];
    f = fopen("textfile.txt","r");
    if(f==NULL)
        exit(1);
    printf("Contents before appendiing: ");
    while(fgets(buff,50,f)!=NULL)
        fputs(buff,stdout);
    fclose(f);
    f = fopen("textfile.txt","a");
    if(f==NULL)
    {
        printf("Unable to open file");
        exit(1);
    }
    printf("\nEnter contents to append (type 'exit'to stop): ");
    do{
        fgets(buff,50,stdin);
        if(strcmp(buff,"exit\n")==0)
            break;
        fputs(buff,f);
    }while(f!=NULL);
    fclose(f);
    f = fopen("textfile.txt","r");
    if(f==NULL)
    {
        printf("Unable to open file");
        exit(1);
    }
    printf("\nContents after appendiing: ");
    while(fgets(buff,50,f)!=NULL)
        fputs(buff,stdout);
    fclose(f);
    return 0;
}

该程序在我的原始机器中提供了这个输出,它应该是这样工作的:

Contents before appendiing: hello world

Enter contents to append (type 'exit'to stop): hello
exit

Contents after appendiing: hello world
hello

Process returned 0 (0x0)   execution time : 10.006 s
Press any key to continue.

虽然它在我的另一台机器上给出了这个:

Contents before appendiing: hello world
Unable to open file
Process returned 1 (0x1)   execution time : 4.452 s
Press any key to continue.

我知道发生这种情况是因为 f 的值变为 NULL,但为什么它发生在一台机器上而不是另一台机器上。我正在运行 Windows 10 并在两台机器上使用 code::blocks IDE。

标签: cfilecodeblocksfopen

解决方案


推荐阅读