写用户输入在C文件 [英] Writing user input to a file in C
本文介绍了写用户输入在C文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我工作的一个程序,用户输入写入一个文件,然后搜索文件,并输出到屏幕上一个特定的记录。
我试着用fgets和也FPUTS,但还没有取得成功。
的#include<&stdio.h中GT;
#包括LT&;&stdlib.h中GT;
#包括LT&;&string.h中GT;
main()的
{
FILE * fileptr;
CHAR ID [30];
焦炭名[47];
AMT的char [50];
INT I;fileptr = FOPEN(C:\\\\ \\\\用户\\\\安德烈文件\\\\ Tester.txt,W);
如果(fileptr == NULL){
的printf(文件无法打开\\ n \\ A \\ A);
FCLOSE(fileptr);
出口(0);
} 的printf(请输入名称:\\ n);
的fscanf(fileptr,%C,名);
的fputs(姓名,fileptr);
FCLOSE(fileptr);
的printf(文件写入成功\\ n);
返回0;
}
解决方案
有几个问题。
- 您正试图从
fileptr
阅读。 - 您正在阅读的只有一个字符,但对待
名称
数组,如果它是正确的读入。
一开始将是:
[...]
的printf(请输入名称:\\ n);
如果(与fgets(姓名,sizeof的名称,标准输入)){
的fputs(姓名,fileptr);
FCLOSE(fileptr);
的printf(文件写入成功\\ n);
}其他{
的printf(读取错误。\\ n);
}
不过,这还不是全部:你已经忘记把错误检查。例如,做你如何知道你的文件写入成功\\ n
如果你不至少检查的fputs的返回值()
?
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. I tried using fgets and also fputs but havent been successful
#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;
}
解决方案
There are several problems.
- You are trying to read from
fileptr
. - You are reading only one character, but treat the
name
array as if it was read in correctly.
A start would be:
[...]
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");
}
But that's not all: you have forgotten to put error checking. E.g., how do you know that your "File write was successful\n"
if you don't check at least the return value of fputs()
?
这篇关于写用户输入在C文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文