【问题标题】:C - Segmentation fault (core dumped), read first N bytes from fileC - 分段错误(核心转储),从文件中读取前 N 个字节
【发布时间】: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 字节

标签: c file fwrite fread


【解决方案1】:

remain 变为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) 的返回值。

【讨论】:

    【解决方案2】:

    当要读取的剩余字节数(在变量remain 中)变得少于1024 时,您出于某种原因尝试读取pos 字节。为什么pos???您应该在最后一次迭代中读取 remain 字节,而不是 pos 字节。

    如果pos 大于1024 并且输入文件仍有额外数据,那么您当然会在最后一次迭代中超出缓冲区。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-02-25
      • 2012-10-12
      • 1970-01-01
      • 1970-01-01
      • 2018-12-09
      • 2022-01-14
      • 2017-02-25
      • 2016-07-12
      相关资源
      最近更新 更多