//#include <QtCore/QCoreApplication>
#include <stdio.h>
#include <stdlib.h>
#include <iostream>
#include <string>
#include "shift.h"
using namespace::std;
int main(int argc, char *argv[])
{
unsigned char tmpBuf;
FILE* fp;
FILE* fp2;
char fname[50];
static unsigned int lSize, count, num;
cout << "Input the filename:" << endl;
cin >> fname;
fp = fopen(fname,"r");
if(fp == NULL) {
cout << "The file does not exist!" << endl;
exit(1);
}
// obtain file size:
fseek(fp , 0 , SEEK_END);
lSize = ftell(fp);
rewind(fp);
cout << "The intput file's size is: " << lSize << endl;
fp2 = fopen("myfile", "w");
while(1){
num = fread(&tmpBuf, 1, 1, fp);
count += num;
// putchar(tmpBuf);
// tmpBuf = cror(tmpBuf, 4);
// tmpBuf = crol(tmpBuf, 4);
fwrite(&tmpBuf, 1, num, fp2);
cout << tmpBuf << " " << num << " " << count << endl;
if (count == lSize){
printf("over\n");
break;
}
}
fclose(fp);
fclose(fp2);
while(1){}
return 0;
//return a.exec();
}
我制作了一个Qt控制台程序并禁用了QtCore,就像上面的代码一样。当读取某个文件时,例如1.txt(仅包含1234567890)成功。但是在阅读其他文件时,例如1.rar,它失败如下:为什么?
答案 0 :(得分:1)
检查从
返回的num的值num = fread(&tmpBuf, 1, 1, fp);
如果它回到0,那就解释了为什么
if (count == lSize){
永远不会真实地让你脱离循环。
至于为什么会发生这种情况,你在“r”模式下打开fname,但rar文件是二进制文件。为此,我建议以“rb”模式打开。如果fread需要txt格式但是达到了EOF指标,那么它将停止前进,因此num = 0并且count不会增加。
我没有可用的窗口来测试这个,但是由于这个原因,stackoverflow上出现了其他问题:
fread/ftell apparently broken under Windows, works fine under Linux