简体   繁体   English

fprintf无法正常工作C

[英]fprintf not working C

I'm trying to make a simple program that writes to a .txt file, but this code won't work. 我正在尝试编写一个简单的程序来写入.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;
}

The printf returns that it's not null, and the int q returns whatever the length of the char is. printf返回其不为null的值,而int q返回任何char的长度。 Why isn't this writing to the file? 为什么不写入文件?

the printf returns that it's not null, printf返回它不为空,

Thats because c is not null , since you have scanned your name string into it. 那是因为c不为null,因为您已将名称字符串扫描到其中。

Why isn't this writing to the file? 为什么不写入文件?

The program is working fine , on my system. 该程序在我的系统上运行正常。

-- Edit -- -编辑-

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

By doing the error handling this way , the exact reason (in your case permissions) , would be displayed, 通过以这种方式进行错误处理,将显示确切的原因(在您的情况下为许可),

Turns out I wasn't running with the correct permissions. 原来我没有以正确的权限运行。 Stupid mistake on my part. 我这是愚蠢的错误。

First off, you've declared c in local scope, so it will never be NULL . 首先,您已经在本地范围内声明了c ,所以它永远不会为NULL If you want to check whether or not the user entered anything, check the length of c after you've scanned in the string: 如果要检查用户是否输入了任何内容,请在扫描字符串后检查c的长度:

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

Second, check whether or not you have permission to write to the current working directory. 其次,检查您是否具有写入当前工作目录的权限。 You should be checking the return value of fopen : 您应该检查fopen的返回值:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM