将文件内容传递到内存中是错误的

时间:2017-07-27 15:30:08

标签: c function file

我想知道为什么我想让函数调用适当加载, 似乎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;
}

谢谢

1 个答案:

答案 0 :(得分:0)

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

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

其次你的load函数返回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 land中的方式