将字符保存到文件 [英] Saving a character to a file
本文介绍了将字符保存到文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
#include<stdio.h>
void read()
{
int i=0 , j=0;
char s[10];
FILE *fp ;
fp = fopen ( "sig.c" , "w+" );
if (fp==NULL)
{fputs("File error",stderr); exit (1);}
fgets (s , 10 , fp) ;
printf("%s \n",s);
fclose(fp);
}
void write()
{
char x1[10] ;
int i =0 ;
char c = "";
FILE *fp;
fp=fopen("sig.c", "wb");
for (i=0 ; i< 10 ;i++)
{
x1[i] = scanf("%c" , &c);
}
char x="f" ,
x2 = "";
for (i=0 ; i< 10 ;i++)
{
x2 = x1[i];
fwrite(&x2, sizeof(x2) , x ,fp);
}
fclose(fp);
}
void main()
{
write();
read();
}
在read func中打印时,此项目错误.为什么代码不将输入的字符复制到sig.txt
This project error when print s in read func. Why does the code not copy the entered char to sig.txt
推荐答案
以"r"模式而不是"w +"模式在读取函数中打开文件.模式"w +"将删除文件的内容(如果存在).那不是你想要的.
x2在您的写入函数中未定义,因此我假设您粘贴了一个简化的副本,但不幸的是它无法编译.
我建议您进行适当的缩进,如果不是为了您自己,那么至少要为阅读程序的其他人使用.
Open the file in your read function with mode "r" instead of "w+". The mode "w+" will delete the contents of your file if it exists. That is not what you want.
x2 is nowhere defined in your write function, so I assume you pasted a simplified copy, which unfortunately does not compile.
I would recommend working with proper indenting, if not for yourself, then at least for others who read your programs.
这篇关于将字符保存到文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文