0

I'm getting a few extra garbage characters after I print out the file I've read into an array.

Here is my code

fp = fopen("load.txt", "r");

if (fp == NULL)
{
    perror("Exiting, an error occured while opening\n");
    exit(EXIT_FAILURE);
}


while((ch = fgetc(fp)) != EOF)
{
    load[i++] = ch;

}

fclose(fp);

for(i = 0; i < 100; ++i)
{

    printf("%c", load[i]);
}

Sample output

The quick brown fox jumped over the lazy dog. ���������0LãUˇ���∞4 ����������@LãUˇ��������������

Notice all of the garbage after the sentence? I'm not sure what is causing this.

Thanks in advance for any help

3
  • 1
    Post the entire relevant code please. Commented Apr 29, 2014 at 17:32
  • Please post the load declaration. Commented Apr 29, 2014 at 17:33
  • 1
    Are you reading about 45 characters (the length of "The quick brown fox jumped over the lazy dog.") and printing 100? Commented Apr 29, 2014 at 17:34

4 Answers 4

2

Well, what did you expect to happen when you print 100 characters in the for loop???

  1. Add i = 0 before the while loop.

  2. Add load[i] = 0 after the while loop.

  3. Replace the entire for loop with printf("%s",load).

Also, assuming that the load array is statically allocated in the same function:

  • Extend the condition of the while loop with && i < sizeof(load)-1.
Sign up to request clarification or add additional context in comments.

Comments

1

You're printing load[i] for all values of i from 0 to 99, but never seem to assign to it beyond where the data read from the file ends. This means the rest of the array has garbage data, which is what you see when you print it.

To fix this, add a terminator symbol to the end of the data read from the file and break the for loop once it comes up.

Comments

0

If you insist on keeping your for loop:

for(int j = 0; j < i; ++j)  //stop at the EOF you got earlier
{
    printf("%c", load[i]);
}

Comments

-1

In C, all strings have a null string terminator, the \0 character. Since you already have the last character loaded, i then you can:

if (i >= 100) i = 100; // bounding checks
load[i] = '\0';

And for printing, you must:

int pos;
while ( pos = 0; pos < i; ++pos)
  printf("%c", load[pos]);

Or...

printf("%s", load);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.