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

标签 c file fwrite fread

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

相关文章:

c - 如何用C从文件中读取特定数量的行

java - 为什么我的代码没有创建新文件?

python - 是否需要关闭json.load中的文件?

c - 将在打开时清除文件内容导致错误 C

PHP 拆分 fwrite 以节省内存

c - 为什么我没有向 Roller2.raw 写入任何内容?

c - 从文件导入链表数据时出现 fscanf 错误

c++ - VOID NTAPI 是什么意思,我在哪里可以找到它的引用资料?

c - 使用递归函数在数组中搜索值

c - 无法通过c程序复制二进制文件