简体   繁体   English

在从文本文件中读取时使用struct时出错

[英]error using struct in reading from a text file

I am a beginner in C programming and trying to use struct to store the related variables and later use them in the main program. 我是C编程的初学者,并尝试使用struct来存储相关变量,然后在主程序中使用它们。 However, when I run the same program without using struct, its running fine. 但是,当我在不使用struct的情况下运行相同的程序时,它运行正常。

The code is presented below, which doesn't show any compilation errors but no output except segmentation fault. 代码如下所示,除了分段错误外,没有显示任何编译错误但没有输出。

#include<stdio.h>

struct test
{
char string1[10000];
char string2[10000];
char string3[10000];
char string4[10000];
}parts;

int main()
{
FILE *int_file;
struct test parts[100000];

int_file=fopen("intact_test.txt", "r");

if(int_file == NULL)
{
    perror("Error while opening the file.\n");
}
else
{
    while(fscanf(int_file,"%[^\t]\t%[^\t]\t%[^\t]\t%[^\n]",parts->string1,parts->string2,parts->string3,parts->string4) == 4)
    {
        printf ("%s\n",parts->string3);
    }
}

fclose(int_file);

return 0;
}

The input file "intact_test.txt" has the following line: AAAA\\tBBBB\\tCCCC\\tDDDD\\n 输入文件“intact_test.txt”包含以下行:AAAA \\ tBBBB \\ tCCCC \\ tDDDD \\ n

Each instance of struct test is 40k so struct test每个实例都是40k

struct test parts[100000];

is trying to allocate 4GB on the stack. 试图在堆栈上分配4GB。 This will fail, leading to your seg fault. 这将失败,导致您的seg错误。

You should try to reduce the size of each struct test instance, give parts fewer elements and move it off the stack. 您应该尝试减小每个struct test实例的大小,为parts更少的元素并将其移出堆栈。 You can do this last point most easily by giving it static storage duration 通过赋予静态存储持续时间,您可以最轻松地完成最后一点

static struct test parts[SMALLER_VALUE];

A single struct takes up 40,000 bytes, and you have 100,000 of these. 单个结构占用40,000个字节,你有100,000个字节。 That comes to 4,000,000,000 bytes, or about 4GB. 这达到了4,000,000,000字节,或大约4GB。 I'm not surprised you are seg faulting 我并不感到惊讶你是故障

Please rethink what you are doing. 请重新考虑你在做什么。 Are you seriously trying to read in 4 strings of 10,000 characters each? 你是否真的试着读4个字符串,每个字符10,000个字符?

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM