gpt4 book ai didi

C - 段错误(核心转储),从文件中读取前 N 个字节

转载 作者:行者123 更新时间:2023-11-30 19:40:25 25 4
gpt4 key购买 nike

我编写了一些代码来从二进制文件中读取第一个 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);
}

最佳答案

remain 变为 <= 1024 并且输入 block 的 if 部分时,您将读取 pos 字节,如果大于 1024 时将写入缓冲区末尾。这就是导致段错误的原因。

您想在此处使用remain:

if(remain <= 1024) {
read = fread(buf, 1, remain, inFile);
} else {
read = fread(buf, 1, 1024, inFile);
}

另外,在返回之前请务必检查 fopen 的返回值,以及 fclose(inFile)fclose(outFile) .

关于C - 段错误(核心转储),从文件中读取前 N 个字节,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35348392/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com