gpt4 book ai didi

c - 将文件内容传递到内存时出现错误

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

我想知道为什么当我认为我调用函数来正确加载时,看来 fread 无法正确读入我的内存块,因此它创建了一个段错误[在加载函数中]!请指出正确的方法

link代码是

#include <math.h>
#include <signal.h>
#include <stdbool.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <strings.h>

bool load(FILE* file, char** content, size_t* length);

int main()
{
// opens file
FILE * file = fopen("test.txt", "r");

// initialises variables
char* content;
size_t length;

// sending arguments to load function
bool receive = load(file, &content, &length);

// debugging content
printf("values of content: %s\n", content);

// debugs length

printf("values of content: %zu\n", length);

// closes file
fclose(file);

// for success
return 0;
}

bool load(FILE* file, char** content, size_t* length)
{

{

// proof checking for the existence of file
if (file == NULL)
{
return false;
}

// perusing to end of file
fseek(file, 0, SEEK_END);

// for approximation of size of file
size_t len = ftell(file);

// returns cursor to beginning of file
fseek(file, 0, SEEK_SET);

// apportions memory on heap for content of file
* content = (char *) malloc (len + 1);

// memory error checking

if(*content == NULL)
{
printf("It's unfortunate\n");

}
// to read into content
fread(* content, sizeof(char), len, file);

// null terminates content
(* content)[len] = 0;

// debugs content
printf(" content contains %s\n", * content);

// debugs length
* length = len;

printf(" length is %d\n", * length);

// if success
return true;

}

// if fail
return false;
}

谢谢

最佳答案

您需要检查文件是否正常打开

  FILE * file = fopen("test.txt", "r");
if(file == NULL)
{
perror("failed to open file: ");
exit(1);
}

其次,你的加载函数返回 false 表示失败,但你没有检查它。做

 bool receive = load(file, &content, &length);
if(!receive)
{
fprintf(stderr, "failed to read file");
exit(1);
}

你所做的事情

  if(*content == NULL)
{
printf("It's unfortunate\n");

}

但是无论如何都要继续。你应该这样做

 if(*content == NULL)
{
printf("It's unfortunate\n");
return false;
}

一般来说,您不会检查您调用的任何函数的返回,fseek、ftell、fread,....当您的程序失败时,您不应该感到惊讶。是的,这是一个无聊的过程,但这就是 C 大陆的方式

关于c - 将文件内容传递到内存时出现错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45355120/

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