GandalfDGrey
GandalfDGrey

Reputation: 321

FILE I/O in C++ throws an error

int main(array<System::String ^> ^args)
{

FILE* fp;
char str[1];
int x = 0;

fp = fopen("C:\\input.txt", "r");

do{
    x = fscanf(fp, "%s", str);

    if (x != -1)  // So that the last string is not printed twice
    {
        printf("%s ", str);
    }

  }while (x != -1);

return 0;

}

This program prints the correct output. BUT after printing, it throws an error in windows saying "Program stopped working". Also IF there is no text in the notepad file i.e if it is blank, then it shows no error. Please explain!

Upvotes: 0

Views: 52

Answers (2)

JackV
JackV

Reputation: 218

First off the statement of you main function looks very much like c++ not C.

Secondly from the statement char str[1]; your declaring an array of characters that is of size 1. This means we can store 1 character inside this array so if we were to have char str[128]; we could store 128 chars in it (Dont forget about the \0).

So this program is trying to read a string into your character array but after the first letter of the string it has no place to store the rest of the string which is why it crashes

Upvotes: 1

David Hoelzer
David Hoelzer

Reputation: 16331

The trouble is that you have a char array of one byte that you are reading strings into. You need to use an array that will be large enough to hold your largest piece of data.

Upvotes: 2

Related Questions