【发布时间】:2016-05-22 18:20:07
【问题描述】:
我编写了一些代码从二进制文件中读取第一个pos 字节并将其写入另一个文件。原来我在运行它时遇到了分段错误。代码如下:
void outputUntillPos(const char * inFileName, const char * outFileName, int pos) {
FILE * inFile = fopen(inFileName, "r");
FILE * outFile = fopen(outFileName, "aw");
char buf[1024];
int read = 0;
int remain = pos;
do {
if(remain <= 1024) {
read = fread(buf, 1, pos, inFile);
} else {
read = fread(buf, 1, 1024, inFile);
}
remain -= read;
fwrite(buf, 1, read, outFile);
memset(buf, 0, 1024);
} while(remain > 0);
}
这里是不是超出范围操作了?
编辑:感谢所有帮助,这是编辑后的代码。
void outputUntillPos(const char * inFileName, const char * outFileName, int pos) {
FILE * inFile = fopen(inFileName, "r");
FILE * outFile = fopen(outFileName, "aw");
char buf[1024];
int read = 0;
int remain = pos;
if((inFile != NULL) && (outFile != NULL)) {
do {
if(remain <= 1024) {
read = fread(buf, 1, remain, inFile);
} else {
read = fread(buf, 1, 1024, inFile);
}
remain -= read;
fwrite(buf, 1, read, outFile);
memset(buf, 0, 1024);
} while(remain > 0 && read > 0);
}
fclose(inFile);
fclose(outFile);
}
【问题讨论】:
-
如果你关闭文件,你会在哪里关闭它们?
-
第 1 步。您没有检查打开的文件。如果他们不这样做,肯定会出现段错误。
-
当要读取的剩余字节数(在变量
remain中)变得少于1024时,您出于某种原因尝试读取pos字节。为什么pos???您应该在最后一次迭代中读取remain字节。 -
@Jacobr365 outFile/inFile应该在读/写完成后关闭,你是说有问题吗?
-
你也没有检查 inFile 至少有 pos 字节