c - 尝试从文件中读取下一行/字符时出现段错误

标签 c memory struct dynamic-memory-allocation file-read

我有一个学校项目,我需要读取 C 语言中的 .ppm 文件并将其存储在结构中以供以后的任务使用。一旦我获得第一行并将其分配给结构变量,如果我尝试再次浏览文件,则会出现错误。这是我的代码:

#include <stdio.h>
#include <stdlib.h>

typedef struct {
    int r, g, b;
} pixels;

typedef struct {
    int width, height, maxColors;
    char *format; //PPM file format
    char *comments;
    pixels *pixels;
} PPM;

PPM *getPPM(FILE * f) {

    // Check if the file is valid. If not then exit the program
    if(f == NULL) {
        perror("Cannot open file: ");
        exit(1);
    }

    PPM *pic = malloc(sizeof(PPM));
    // If memory allocation fails, exit the program.    
    if(!pic) {
        perror("Unable to allocate memory for structure");
        exit(1);
    }

    // Store the first line of file into the structure
    char *fileFormat;

    if(fgets(fileFormat, sizeof(fileFormat), f) != NULL) {
        // If it is a valid .ppm format, then store it in the structure
        if(fileFormat[0] == 'P') 
            pic->format = fileFormat;
    } else {
        perror("Unable to read line from the input file");
        exit(1);
    }

//Errors start here
    int c = getc(f);
    while(c != EOF)
        c = getc(f);

/*
    char *comments;

    if(fgets(comments, sizeof(comments), f) != NULL) {
        printf("%s\n", comments);
    } else {
        perror("Unable to read line from the input file");
        exit(1);
    }
*/
    fclose(f);
    return pic; 
}



int main(int argc, char **argv) {

    PPM *p = getPPM(fopen(argv[1], "r"));
    printf(" PPM format = %s",p->format);
    return 0;
}

我尝试从文件中获取单个字符。我尝试使用 fgets 读取整行,就像我在上一步(对于 fileFormat)中所做的那样,但每次它都会给出段错误。我尝试查看其他示例,但我无法找出问题所在。我已经花了几个小时了,因此我们将不胜感激!

难道内存分配方式有问题?或者当我尝试读取新行时是否需要提供某种指向文件的指针?我尝试在手册页中寻找答案,但我什么也没弄清楚。

附注while(c != EOF) { c = getc(f);下一个注释步骤只是看看它是否有效。我想将 .ppm 文件中的所有信息放入 PPM 结构中。

最佳答案

您正在读取一个未初始化的指针,因此这将会崩溃。您需要一个缓冲区:

char *fileFormat = malloc(SIZE_OF_FILE_FORMAT);

此外,sizeof(fileFormat) 返回指针的大小,在本例中这不是您想要的。您需要指针指向的缓冲区的大小。

关于c - 尝试从文件中读取下一行/字符时出现段错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54677562/

相关文章:

c - 在c程序中包含tk.h和tcl.h

c - C 中的质数

c - linux同进程下的线程如何分配stack或内存

iPhone 内存,该相信什么?

c++ - 具有结构数据类型的链表

制造商的 C 代码中断设置

c - C中的_Thread_local存储类说明符?

html - 如何在html文件golang中获取这个值

c++ - 从 C++ 设置变量时 QML 内存泄漏

go - 将结构转换为 slice 结构