0

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!!

Abra
  • 19,142
  • 7
  • 29
  • 41
  • Why work with a ```FILE *``` that could potentially be ```NULL```? – Harith Jan 15 '23 at 05:35
  • Also see: [Why is “while( !feof(file) )” always wrong?](https://stackoverflow.com/questions/5431941/why-is-while-feoffile-always-wrong) – Harith Jan 15 '23 at 05:36
  • Use fgets() instead of fscanf then remove \n – AndersK Jan 15 '23 at 05:43
  • 1
    Your example of text is one column, with many rows. And notice that your array `str` has room for only 101 words, so if you read 102 rows you will write past the end of the array, which can cause the program to fail in unpredictable ways. – Beta Jan 15 '23 at 05:46
  • closing this because of the eof test is not really very helpful. Thats not why it fails. Its like closing all c++ questions that include 'using namespace std' as a dup of 'why is using namespace std so bad' – pm100 Jan 28 '23 at 21:39

1 Answers1

1

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.