2013-03-07 90 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"); 
}