将用户输入写入C中的文件

时间:2011-11-13 22:21:44

标签: c

我正在开发一个程序,用于将用户输入写入文件,然后在文件中搜索特定记录并将其输出到屏幕。 我尝试过使用fgets和fput但是还没有成功

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
main ()
  {
FILE *fileptr;
char id [30];
char name [47];
char amt[50];
int i;

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;
  }

1 个答案:

答案 0 :(得分:0)

有几个问题。

  1. 您正试图阅读fileptr
  2. 您只阅读一个字符,但请将name数组视为正确读取。
  3. 一个开始是:

      [...]
      printf("Enter name: \n");
      if (fgets(name, sizeof name, stdin)) {
        fputs(name,fileptr);
        fclose(fileptr);
        printf("File write was successful\n");
      } else {
        printf("Read error.\n");
      }
    

    但并非全部:你忘记了错误检查。例如,如果你不至少检查"File write was successful\n"的返回值,你怎么知道你的fputs()

相关问题