2013-03-07 88 views
0

我正在試圖編寫一個簡單的程序來寫入一個.txt文件,但是這段代碼不起作用。fprintf無法正常工作C

#include <stdio.h> 
#include <string.h> 
#include "main.h" 

int main(int argc, const char * argv[]) 
{ 
    FILE *f = fopen("text.txt", "w+"); 
    char c[256]; 
    printf("What's your name?\n"); 
    scanf("%s", c); 
    fflush(f); 
    if (c!=NULL) 
    { 
     printf("not null\n"); 
     int q = fprintf(f, "%s", c); 
     printf("%d", q); 
    } 
    else 
    { 
     printf("null\n"); 
    } 
    printf("Hello, %s\n", c); 
    fclose(f); 
    return 0; 
} 

printf回報,它不爲空,且int q返回無論字符的長度。爲什麼不寫這個文件?

+1

我想上的Microsoft Visual C++程序,它工作正常。我在工作目錄中觀察到一個text.txt文件。你能分享關於你的環境的更多細節嗎?另外,你爲什麼包含'main.h'? – Ganesh 2013-03-07 03:01:38

+2

'c'不會爲空,不需要檢查。相反,確保'f'不爲空。 – perreal 2013-03-07 03:01:49

+1

並打開一些編譯器警告... – 2013-03-07 03:03:26

回答

0

原來我沒有使用正確的權限運行。對我來說愚蠢的錯誤。

1

中的printf返回它不爲空,

那是因爲c不是空的,因爲你已經掃描你的名字串進去。

爲什麼不寫這個文件?

該程序工作正常,在我的系統上。

- 編輯 -

FILE *f = fopen("text.txt", "w+"); 
if (NULL == f) 
    perror("error opening file\n"); 

通過做錯誤處理這樣,確切的原因(在你的案件的權限),將顯示,

0

首先,你聲明c在本地範圍內,所以它永遠不會是NULL。如果要檢查用戶是否沒有輸入任何東西,檢查c長度將字符串在掃描完成後:

if (strlen(c) == 0) { 
    /// 
} 

其次,檢查你是否擁有寫權限的當前工作目錄。你應該檢查返回值的fopen

if (!f) { 
    fprintf(stderr, "Failed to open text.txt for writing\n"); 
}