c - 在 C 编程中将用户输入写入文件

标签 c file

我正在开发一个程序,将用户输入写入文件,然后在文件中搜索特定记录并将其输出到屏幕。

我尝试使用 fgets 和 fputs,但都没有成功。这是我目前所拥有的。

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

main ()
{
    FILE *fileptr;
    char id [30];
    char name [47];
    char amt[50];

    fileptr = fopen("C:\\Users\\Andrea\\Documents\\Tester.txt", "w");
    if (fileptr == NULL) {
        printf("File couldn't be opened\n\a\a");
        fclose(fileptr);
        exit(0);
    }

    printf("Enter name: \n");
    fscanf(fileptr, "%c", name);
    fputs(name, fileptr);
    fclose(fileptr);
    printf("File write was successful\n");
    return 0;
}

最佳答案

使用:

fscanf(stdin, "%s", name);

但更好的是,如 kol 所述,改用 scanf。这是因为 scanf() 旨在从屏幕读取用户响应,而 fscanf() 用于扫描任何输入流(通常是文件)。

并且该语句应该从屏幕 (stdin) 中读取,而不是从文件中读取(该文件仅以“写入”方式打开)。

关于c - 在 C 编程中将用户输入写入文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8115944/

相关文章:

python - 编写一个修改参数的 python c 扩展

c++ - 在 "a"(追加)模式下打开文件时 fseek 不起作用

java - 文件java替换字符

java - 系统找不到指定的Java文件

php - 使用 php 将 postgres 输出写入文件

c++ - 是否有像 docco 这样的 C/C++ 源代码文档生成器?

c - 修改C中的字符串数组

c - 寻找一种从CSV文件中读取8*8矩阵并存储它的方法

c - Arduino Error all of overloaded ‘println(long unsigned int (&)())’ is ambiguous 错误

c - 处理输入文件时如何向前看(处理 2 行)