这是实验程序: FILE *pf; if (pf=fopen("1.txt","w")) { CString str="a:This is the first."; CString str1="b:This is the second."; CString str3="c:This is the third."; CString str4="d:This is the fourth."; CString str2="Hello everybody!"; str+="\r\n"+str1+"\r\n"+str2+"\r\n"+str4+"\r\n"+str2; AfxMessageBox(str); fseek(pf,0,SEEK_END); fwrite(str,1,strlen(str),pf); fclose(pf); } 并不是在文件后面追加,追加的话,pf=fopen("1.txt","a") 对不对?
FILE* pFile = fopen("F:\\11.txt", "w+");
if(pFile)
{
char buf[] = "hello\r\nworld";
fwrite(buf, 1, strlen(buf), pFile);
fclose(pFile);
}
打开和写入读取的函数是必须成对的吗?
-----------------------------------
可以的打开和写入读取的函数是必须成对的吗?
-----------------------------------
fopen要和fclose成对, 跟其它函数没关系,
想读就fread,fgets,想写就fwrite,fputs
现在是第一次写换一行,第二次换两行,第三次换三行……
咋了?
int j;
int count = ? //你要写的行数
FILE *fp = fopen(....);
for (i = 0; i < count; i ++) {
fwrite(databuf, 1, datalen, fp); //databuf 你要写入的数据;datalen 数据长度
for(j = 0; i <= i; j++)fwrite("\r\n", 1, 2, fp);
}
fclose(fp);
if (pf=fopen("5.txt","w"))
{
totalStr="Start:\r\n"+str1+"\r\n"+str2+"\r\n"+str3+"\r\n"+str4+"\r\n"+strLocation;
fwrite(totalStr,1,strlen(totalStr),pf);
fclose(pf);
}
else
AfxMessageBox("Write failed!");代码是这样的
“第一次写换一行,第二次换两行”是说运行一次
想要只是换行,每运行一次的写不是都覆盖掉的吗?
这是运行的结果:
Start:IP:192.169.0.15ID:TPPC:TPName:Second:
建议你找一本C语方基础看看
FILE *pf;
if (pf=fopen("1.txt","w"))
{
CString str="a:This is the first.";
CString str1="b:This is the second.";
CString str3="c:This is the third.";
CString str4="d:This is the fourth.";
CString str2="Hello everybody!";
str+="\r\n"+str1+"\r\n"+str2+"\r\n"+str4+"\r\n"+str2;
AfxMessageBox(str);
fseek(pf,0,SEEK_END);
fwrite(str,1,strlen(str),pf);
fclose(pf);
}
并不是在文件后面追加,追加的话,pf=fopen("1.txt","a")
对不对?
另外,你的程序错误在于用了"w"方式打开的,其实,内容不是被覆盖了,
而是在打打开时就被清空了, 可以用“a”或者"r+"方式打开,
用“r+”方式打开,需要fseek(pf,0,SEEK_END),MSN上有很详细的解
释。在编程的路上,你还有很长的路要走