We're a community of 1076K IT Pros here for help, advice, solutions, professional growth and fun. Join us!
1,075,924 Members — Technology Publication meets Social Media
Username:
Password:
Lost login information?
Start New Discussion Reply to this Discussion

reading file from offset in c

I am trying to read a file from an offset till end of file:

int i,sizeb=210;
char *buffer;  //[1024];
FILE *f;


f = fopen("myfile", "rb");

printf("Reading file.\n");

fseek(f, sizeb, SEEK_SET);
long s = ftell(f);
//rewind(f);

fread(buffer, s, 1, f);
fclose(f);

But I never get the right result.

Also when I use a large buffer like buffer[10240000] it wil crash immediately upon running it.

Maybe someone can help me fix it.

2
Contributors
2
Replies
4 Hours
Discussion Span
1 Year Ago
Last Updated
4
Views
coder_10
Newbie Poster
14 posts since Oct 2011
Reputation Points: 10
Solved Threads: 0
Skill Endorsements: 0

The large buffer is causing you to crash because it is being allocated on the stack and you don't have enough stack space. If this is Linux/Unix you can fix that with the system ulimit command, unless the sysadmin has restricted you in some way. In any case, this is non-functional code. What does the char* buffer point to? So, you are seeking 210 bytes into the file, and have commented out rewind(), and then read 240 bytes, but it would start there and not at the beginning of the file. So, create a buffer of some reasonable size (up to 1MB may be ok - you are using 10M, and most systems limit stack to 8M or less), seek to the position that you want to start at, and then start reading in a loop until you get to feof(f). If you want to read it all into one buffer, then allocate buffer on the heap using malloc/calloc function calls.

If you want to know where the end of the file may be in bytes from the beginning, then try using fseek(f, 0L, SEEK_END), then ftell(). That will tell you just how much buffer space you need.

rubberman
Posting Maven
2,571 posts since Mar 2010
Reputation Points: 365
Solved Threads: 305
Skill Endorsements: 52

Could you write that out in code?

And the idea is to start reading from offset 210 till the end of the file. Not from the beginning.

I tried 1mb buffer size but than it crashes. But regardless, what if my file is larger than 1mb, what than?

coder_10
Newbie Poster
14 posts since Oct 2011
Reputation Points: 10
Solved Threads: 0
Skill Endorsements: 0

This article has been dead for over three months: Start a new discussion instead

Post: Markdown Syntax: Formatting Help
 
You
View similar articles that have also been tagged:
 
© 2013 DaniWeb® LLC
Page rendered in 0.0758 seconds using 2.64MB