I can't read and display txt file

68 Views Asked by At

I'm trying to read a file from txt docs and display the data, but when I run the code, it displays nothing and just shows like this:

enter image description here

I'm not sure where the problem is with my code, but perhaps the problem is because I need to display 4000 columns of data so the program cannot read and display it. I tried to use another sample txt with 10 columns of data and the code worked but not with 4000 columns of data.

This is my code :

char str [101][101];
FILE *fin = fopen ("test.txt", "r");
int count = 0;
while (!feof(fin)){
    fscanf (fin, "%s", str[count]);
    count++;
}
fclose(fin);
for (int i = 0 ; i < count ; i++){
    printf("%s\n", str[i]); 
}

This is data I want to read and display (4000 columns data)

Bali
Paris
Japan
Nepal
India
Rusia
Malaysia
Thailand 
England
etc....

Thank you in advance!!

1

There are 1 best solutions below

1
Patrice Thimothee On

I haven't tried to run the code. You read a file line by line and put every line within str. However, str can only contain a maximum of 101 lines, with each iteration not exceeding 100 chars.

Increase the value of str to at least 4000.

str[4500][101]

EDIT:

The question has been flagged as duplicate; however, the problem here is linked to how the C language works. In this example, we have a static two-dimensional array for which C reserved some memory on the stack. As C tries to use more memory than allocated, the O.S. will inform the process that it does not have access to the location. Which makes C raise an exception at runtime.

I think bringing this precision to those who learn C is essential to avoid confusion.