2013-09-27 48 views
0

我到目前爲止只使用Linux來編寫代碼(基本上,使用gate和gcc命令行)。我想進入Windows編程,因爲我有權訪問運行Win7的所有更強大的機器。Code ::使用MinGW編譯器的模塊 - fprintf導致空文件

所以我下載了codeblocks和minGW。你好世界運行良好,但是當涉及到打印文件時,它只是給我一個空文件。我是否犯了一個新手錯誤?它創建了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; 
} 

回答

2

這是不正確的:

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

你的if語句應該是:

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

所以文件「TESTFILE.TXT」將被打開正確,你會得到預期的輸出:

This is a test 9 
+0

確實是新手錯誤。謝謝。 – KBriggs

+0

@KBriggs很高興能有所幫助,在C中賦值運算符返回一個值,if((test = fopen(「testfile.txt」,「w」))== NULL)'的總值等於返回值爲[fopen()](http://pubs.opengroup.org/onlinepubs/009695399/functions/fopen.html),其值爲NULL。但在你的情況下,'test'總是指向一個FILE對象的NULL指針,'fprintf()'將無法寫入...... – boleto