CoffeeRain
CoffeeRain

Reputation: 4522

fread() puts weird things into char array

I have a file that I want to be read from and printed out to the screen. I'm using XCode as my IDE. Here is my code...

fp=fopen(x, "r");
char content[102];
fread(content, 1, 100, fp);
printf("%s\n", content);

The content of the file is "Bacon!" What it prints out is \254\226\325k\254\226\234.

I have Googled all over for this answer, but the documentation for file I/O in C seems to be sparse, and what little there is is not very clear. (To me at least...)

EDIT: I switched to just reading, not appending and reading, and switched the two middle arguments in fread(). Now it prints out Bacon!\320H\320 What do these things mean? Things as in backslash number number number or letter. I also switched the way to print it out as suggested.

Upvotes: 2

Views: 9760

Answers (4)

Sergey Kalinichenko
Sergey Kalinichenko

Reputation: 726849

You are opening the file for appending and reading. You should be opening it for reading, or moving your read pointer to the place from which you are going to read (the beginning, I assume).

FILE *fp = fopen(x, "r");

or

FILE *fp = fopen(x, "a+");
rewind(fp);

Also, fread(...) does not zero-terminate your string, so you should terminate it before printing:

size_t len = fread(content, 1, 100, fp);
content[len] = '\0';
printf("%s\n", content);

Upvotes: 9

user418748
user418748

Reputation:

Maybe:

fp = fopen(x, "a+");
if(fp)
{
    char content[102];
    memset(content, 0 , 102);

    // arguments are swapped.
    // See : http://www.cplusplus.com/reference/clibrary/cstdio/fread/
    // You want to read 1 byte, 100 times
    fread(content, 1, 100, fp);

    printf("%s\n", content);
}

Upvotes: 1

Some programmer dude
Some programmer dude

Reputation: 409364

A possible reason is that you do not terminate the data you read, so printf prints the buffer until it finds a string terminator.

Upvotes: 0

arrowd
arrowd

Reputation: 34411

I suppose, you meant this:

printf("%s\n", content);

Upvotes: 2

Related Questions