0

我正在尝试制作一个写入 .txt 文件的简单程序,但此代码不起作用。

#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返回它不为空,并且返回无论 char的int q长度是多少。为什么不写入文件?

4

3 回答 3

1

printf 返回它不为空,

那是因为 c 不是 null ,因为您已将名称字符串扫描到其中。

为什么不写入文件?

该程序在我的系统上运行良好。

- 编辑 -

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

通过以这种方式进行错误处理,将显示确切的原因(在您的情况下是权限),

于 2013-03-07T03:03:21.837 回答
0

首先,您已经c在本地范围内声明,所以它永远不会是NULL. 如果您想检查用户是否输入了任何内容,请检查c您在字符串中扫描后的长度:

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

其次,检查您是否有权写入当前工作目录。您应该检查的返回值fopen

if (!f) {
    fprintf(stderr, "Failed to open text.txt for writing\n");
}
于 2013-03-07T03:06:35.523 回答
0

原来我没有使用正确的权限运行。我犯了愚蠢的错误。

于 2013-03-07T03:02:22.133 回答