在C编程中将用户输入写入文件 [英] Writing user input to a file in C programming

查看:43
本文介绍了在C编程中将用户输入写入文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I am working on a program to write user input to a file and then search for a specific record in the file and output it to the screen.

我尝试使用fgets和fputs,但没有成功.这就是我到目前为止所拥有的.

I tried using fgets and also fputs, but I haven't been successful. Here's what I have so far.

#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()则用于从任何输入流(通常是文件)进行扫描.

But better still, use scanf instead, as kol mentioned. This is because scanf() is designed to read the user response from the screen while fscanf() is for scanning from any input streams (which are usually files).

该语句应该从屏幕(stdin)读取,而不是从文件(仅以写入"打开)中读取.

And the statement should be reading from the screen (stdin), not from the file (which was opened as "write" only).

这篇关于在C编程中将用户输入写入文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆