GrinReaper
GrinReaper

Reputation: 93

Junk data when using fread

I'm trying to use fread to get lines of data from a text file. The first thing my program does is open the text file, and determines the byte offset of the beginning of each line.

The byte offset of line 1 is 0, and is stared in offset[1]. The byte offset of line 2 might be 45 bytes, and that will be stored in offset[2], and so forth. The byte offset of the EOF is stored in array[lastline + 1]

In a loop, I'm trying to use these statements to print what I want:

fseek(fptr, ptr[line], SEEK_SET);
fread(str, sizeof(char),  (  (ptr[line + 1] - ptr[line]) - 2) / sizeof(char) , fptr);
printf("%03ld %03ld %s\n", line, ptr[line + 1 ] - ptr[line], str);

my fread statement uses ((ptr[line + 1] - ptr[line]) - 2) / sizeof(char) for the number of elements to print. I have several concerns here.

  1. I'm using -2 to try and account for the newline and carriage return. My professor said that I have the two extra bytes/line because of the newline and carriage return. Should I be trying to take care of them this way? Does it make my program less portable?
  2. My program will print a range of lines or a single line upon user request. When I print more than one line, the second line's output is really mangled.

    Printing lines 2 to 4 ... LINE: 2 002 005 123 003 011 123456789¼ü|♥ 004 007 123456789¼ü|♥

The first column is line number, the second is the BYTE LENGTH OF THAT LINE, not the byte offset. When I print only one line, it's sometimes mangled, but not always.

Printing line 1...
001 008 123456☻

I'm thinking that I'm either not using fread properly, or I'm doing something really bizarre with the way I'm reading from the text file and storing it into the temp string before printing. What seems to be the problem?

EDIT:

OK, so my loop for using fread was already assigning the return to some variable. I didn't know what to do with it until just now. Following the suggestions in the comments, I'm using

count = fread(stuff);
str[count] = '\0';

This seems to have fixed it.

Upvotes: 1

Views: 1148

Answers (2)

paulsm4
paulsm4

Reputation: 121799

I think you're probably forgetting about the null terminator

char s[] = "ABC"; // {'A', 'B', 'C', '\0'}

s[3] = '\0';

Upvotes: 2

cnicutar
cnicutar

Reputation: 182674

You need to say str[something] = 0 at some point, before using str. If you are dealing with a text file it will most certainly not contain a 0 terminator.

That something could be the number of characters returned by fread.


Side note: sizeof(char) looks ridiculous since it's 1 by definition.

Upvotes: 1

Related Questions