【发布时间】:2014-04-21 19:52:40
【问题描述】:
我正在尝试学习编写数据(字符、整数和字符串)的语法。我研究了以下链接http://web.cs.swarthmore.edu/~newhall/unixhelp/C_files.html的内容,编写了如下代码。该代码的目的是以下列方式将数据存储在文本文件中:
33
你好
15
好的
如果我输入 33、Hello、15、Ok 和 0。但是当我在运行程序后打开它时,文本文件完全是空白的。 这里有没有人擅长将数据存储在文本文档中,可以给我一些提示我做错了什么?或者,如果有任何其他你知道的好教程?
我的测试代码附在下面[我可以毫无问题地编译和运行它,只是它没有做我期望的事情:( ]
char stdin_buff[20];
int stdin_int;
FILE *fp;
char *filename = "data.txt"; //name of the textfile where the data should be stored
void handle_String_input(char msg[]){
fp = fopen(filename, "w"); //opens the text file in write mode
if(fp==NULL){
printf("Unable to open the file! \n");
}
fseek(fp, 1, SEEK_END); //seek the end of the text file
fputs(msg,fp); //writes the message to the text file
putc('\n',fp); //new line in the text document
putc('\n',fp); //new line in the text document
fclose(fp); //closes the text file
}
void handle_Integer_input(int nbr){
fp = fopen(filename, "w"); //opens the text file in write mode
if(fp==NULL){
printf("Unable to open the file! \n");
}
fseek(fp, 1, SEEK_END); //seek the end of the text file
fputc(nbr,fp); //writes the nbr into the text file
putc('\n',fp); //new line in the text document
fclose(fp); //closes the text file
}
void main(){
while(1){
memset(stdin_buff,'\0',10); //clears the content of stdin_buff
printf("Enter an integer(enter 0 to exit): ");
fgets(stdin_buff,9,stdin); //retrieves an input from keyboard(the user is expected to only use the numbers 0-9)
stdin_int=atoi(stdin_buff);
handle_Integer_input(stdin_int);
if(stdin_int==0){
break;
}
memset(stdin_buff,'\0',10); //clears the content of stdin_buff
printf("Enter a string(enter 0 to exit): ");
fgets(stdin_buff,9,stdin); //retrieves input from keyboard
handle_String_input(stdin_buff);
if(stdin_buff[0]=='0'){
break;
}
}
}
我错过/不明白什么?任何有关改进的建议表示赞赏!
【问题讨论】:
-
@Jongware:我看不出这个问题和 MPI 之间有直接的关系......
-
"您反复打开输出文件以进行写入。默认情况下,这会将其截断为 0 字节。"
标签: c text text-files