Read a specific number of characters in the text file using fread and fseek

advertisements

Let's say I have a text file like this

This is a text file which contains some numbers.

So I want to use fseek and fread to read some parts of the text file. For example, from position 0 to 13, I'll get "This is a text". Then from position 14 to 24, I'll get " file which", then from position 25 to the end of file, I'll get " contains some numbers."

I've tried to use fseek and fread but I've got some additional weird characters like "This is a text?"

My attempt to use fseek and fread:

src = fopen(textfile, "r");
int chunksize = data[i].end - data[i].start;
char *buffer = malloc(sizeof(chunksize));

seek(src, data[i].start, SEEK_SET);
fread(buffer, 1, chunksize, src);
fseek(src, 0, SEEK_SET); // seek back to beginning of file

where data[i].start is the start position to read to part and data[i].end is the end position to stop. For example, from 14 to 24, I'll get " file which". start is 14 and end is 25.


You need to rewrite your code approximately as follows:

src = fopen(textfile, "r");
int chunksize = ...
char *buffer = malloc(chunksize + 1);
fseek(src, data[i].start, src);
int len = fread(buffer, 1, chunksize, src);
*(buffer+len) = '\0';

So, we have the following, a buffer containing what was read from the file. We have a string terminator following the content read (which may be less than you asked for). If you now issue:

print("%s\n", buffer)

You will get exactly what you read from the file.

PS: It is a good idea to check the return from the fopen() to be sure that the file opened properly, and the return from malloc() to ensure that memory was allocated successfully, and the return from fread() to ensure that the correct amount of data was read.