【问题标题】:Code::Blocks with MinGW compiler - fprintf results in empty file带有 MinGW 编译器的 Code::Blocks - fprintf 导致空文件
【发布时间】:2013-09-27 15:22:08
【问题描述】:

到目前为止,我只使用 Linux 进行编码(基本上是 gcc 和 Kate 的命令行)。我想在 Windows 中编程,因为我可以访问所有更强大的机器来运行 Win7。

所以我下载了代码块和 minGW。 Hello world 运行良好,但在打印要归档的内容时,它只会给我一个空文件。我犯了新手错误吗?它创建了testfile.txt,但执行后文件为空。

代码:

#include<stdio.h>
#include<stdlib.h>
int main(int argc, char **argv)
{
    FILE *test;
    if (test=fopen("testfile.txt","w")==NULL)
    {
            printf("Open Failed\n");
            abort();
    }
    int i=9;
    fprintf(test,"This is a test %d\n",i);
    fclose(test);
    return 0;
}

【问题讨论】:

    标签: c windows mingw codeblocks


    【解决方案1】:

    这是不正确的:

    if (test=fopen("testfile.txt","w")==NULL)
    

    你的 if 语句应该是:

     if ((test=fopen("testfile.txt","w"))==NULL)
    

    因此文件 "testfile.txt" 将被正确打开,您将获得预期的输出:

    This is a test 9 
    

    【讨论】:

    • 确实是新手错误。谢谢。
    • @KBriggs 很高兴能提供帮助,在 C 中,赋值运算符返回一个值,if((test=fopen("testfile.txt","w"))==NULL) 的总值等于 fopen() 的返回值,检查为 NULL。但在您的情况下,test 始终是指向 FILE 对象的 NULL 指针,而fprintf() 将无法写入...
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-08-23
    • 2011-08-02
    相关资源
    最近更新 更多