今天写计网实验GBN要读入和写文件,且由于要以帧为单位传输,所以必须分块读取有大小上限的数据,因此之前写的fscanf用不了。于是用了配上fseek的fread,其中要注意打开windows下的txt,fopen必须用rb或wb,不然读到换行时会出错(换行的字符大小出现不同)。且读入中文时终端会显示乱码但没关系,写入文件时正常。
最终代码:
#include<cstdio>
#include<cstring>
using namespace std;
#define FILE_NAME_MAX_SIZE 512 //文件名最大长度
#define buf_len 5 //缓冲区大小
int main()
{
char file_name[FILE_NAME_MAX_SIZE + 1] = { 0 };
char databuf[buf_len+1]={0};
printf("------------------\nEnter the file name to transfer:\n");
scanf("%s",&file_name);
printf("------------------\n");
int i=1,unReadLen=0;
int count=0;
//-----------------------------------------
//fopen,fwrite读文本文件一定要用rb和wb,不然碰到换行读错、写错
FILE* fp = fopen(file_name, "rb");
FILE*fp2=fopen("2.txt","wb");
//------------------------------------------
if (fp == NULL)
{
printf("File:%s Not Found!", file_name);
}
else{
while(1){
//设置偏移量为已经读取的文件长度
fseek(fp, unReadLen, SEEK_SET);
//开始读取指定长度的文件
count = fread(databuf, 1,buf_len, fp); //每次读1大小数据,分buf_len次来读。fread()返回的是实际读取到次数(当次数小于设定的buf_len次时表示读完或错误)(只有在如该代码size=1时才等于字节数)
unReadLen += count*1; //新偏移量
printf("count:%d\n",count);
printf("unReadLen:%d\n",unReadLen);
printf("%d:%s\n",i++,databuf);
fwrite(databuf,1,count,fp2);//写
memset(databuf,0,sizeof(databuf));
if(count<buf_len) //读完
{
printf("end\n");fclose(fp);fclose(fp2);break; //无fclose不会写入文件
}
}
}
}
参考:
[重要]C中fread()函数的返回值
在线等, 请教大神如何使用fread分段读取文件.
巧用块读写实现fread循环读写文件[原]
windows下使用fread/fwrite的文件指针跳转错误问题
windows下文本文件读取和二进制文件读写的区别
文本文件和二进制文件的差异和区别