tags:

views:

52

answers:

4

I want to read some data from the file, the data will have different sizes at different times.

If I use the below code, then:

char dataStr[256];

fread(dataStr, strlen(dataStr), 1, dFd);

fread is returning 0 for the above call and not reading any thing from the file.

But, if I give size as 1 then it successfully reads one char from the file.

What should be the value of size argument to the fread() function when we do not know how much is the size of the data in the file?

+1  A: 

You should use:

fread(dataStr, 1, sizeof dataStr, dFd);

to indicate that you want to read the number of bytes equal to the size of your array buffer.

The reason why your code doesn't work is that strlen() finds the length of a NULL-terminated string, not the size of the buffer. In your case, you run it on an uninitialized buffer and simply get lucky, your first byte in the buffer is NULL, so strlen(dataStr) returns 0, but is just as likely to crash or return some random number greater than your buffer size.

Also note that fread() returns the number of items read, not the number of characters (I swapped the second and the third arguments so that each character is equivalent to one item).

Alex B
+2  A: 

strlen counts the number of characters until it hits \0.
In this case you probably hit \0 on the very first character hence strlen returns 0 as the length and nothing is read.

You sould use sizeof instead of strlen.

Sani Huttunen
+2  A: 

You can't do that, obviously.

You can read until a known delimiter, often line feed, using fgets() to read a line. Or you can read a known-in-advance byte count, using that argument.

Of course, if there's an upper bound on the amount of data, you can read that always, and then somehow inspect the data to see what you got.

Also, in your example you're using strlen() on the argument that is going to be overwritten, that implies that it already contains a proper string of the exact same size as the data that is going to be read. This seems unlikely, you probably mean sizeof dataStr there.

unwind
A: 

fread returns the number of successfully readed numblocks. You can:

if( 1==fread(dataStr, 256, 1, dFd) )
  puts("OK");

It reads ever the full length of your defined data; fread can't break on '\0'.

The issue i am facing is that i don't know exactly what is the size of the data in the file. (The file basically will have a number as it content, so it can be 8 or 3445 or any other number). Now what is happening is the it reads some junk after reading the number when i gave sizeof as the size argument. How can i read the exact data (in this case number) without knowing its sizes from the file.
vikas