【问题标题】:C code is segfaulting while using fseek [closed]使用 fseek 时 C 代码出现段错误 [关闭]
【发布时间】:2016-08-09 00:27:26
【问题描述】:

我有一段代码,我认为我在过去编译并成功,但现在我遇到了段错误,我不明白为什么。

FILE *numbers = fopen("./e13.txt", "r");

//seeking the end of the file to get the correct size for the string
//I will store
fseek(numbers, 0, SEEK_END);
long fsize = ftell(numbers);
fseek(numbers, 0, SEEK_SET);

//Allocating memory to the string
char *string = malloc(fsize + 1);

我正在尝试将文件读入内存,以便获得适当的大小并尝试malloc 那个内存量。我认为这是 fseek 函数中的段错误,但我不明白为什么......

【问题讨论】:

  • 也许是时候开始检查错误了。
  • 我该怎么做?
  • 第 1 步。阅读每个手册页以找出它在错误时返回的值。例如fopen man page。步骤 2. 检查这些错误。例如if (!numbers) { perror("fopen failed"); exit(1); }
  • @deltaskelta:通过阅读手册!

标签: c gcc segmentation-fault


【解决方案1】:

fopen 如果无法打开文件,可以返回NULL。这可能就是这里发生的事情。你应该像这样检查它:

if(!numbers){/*report error and exit*/}

另外,如果您只是想获取文件的大小,如果您的系统支持,请考虑使用stat。如果您还想打开它并将其全部读入内存,如果您的系统支持,我建议使用mmap

#include <sys/mman.h>
#include <sys/stat.h>
#include <fcntl.h>

int fd = open("e13.txt", O_RDONLY);
if(!fd){/*report error and exit*/}
size_t len;
{
    struct stat stat_buf;
    if(fstat(fd, &stat_buf)){
        close(fd);
        /*report error and exit*/
    }
    len = stat_buf.st_size;
}
void *map_addr = mmap(NULL, len, PROT_READ, MAP_PRIVATE, fd, 0);
close(fd);
if(!map_addr){/*report error and exit*/}
/*do work*/
munmap(map_addr, len);

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2019-12-31
    • 1970-01-01
    • 2020-07-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-07-30
    相关资源
    最近更新 更多