BoredPerson BoredPerson - 1 year ago 57
C Question

Read C function

So I am writing a function that reads from a file, and places the bytes into a temp buffer. Then writes it to the param buffer at an offset.

I may be understanding read wrong, but I want to read, every time the function is called, the next "size" of bytes in the file should be read. But it is reading the same 1024 bytes every time.. I have a feeling this is because of the scope, how do i fix or that I need to put an a offset?

Also is there any way for check how many characters were read, when read hits EOF?

int addChunk(char* buffer, int size, int index){
char buf[size + 1];
int fdIn, cnt, i;
//int count = 0;

if (argcG < 2) {
fdIn = 0;
else if ((fdIn = open(sString, O_RDONLY)) < 0) {
fprintf(stderr, "file open: %s\n", sString);

cnt = read(fdIn, buf, size);
if(cnt == 0){
buf[size] == '\0';

// if (fdIn > 0){

for(int i = 0; i < ((cnt == 0)? size : cnt); i++){
if(buf[i] == '\0'){

/* for(int i = (index * size) - 1; i < size; i++){
buffer[i] = buf[j];
printf("Counted %d bytes \n", cnt);
return cnt;

Answer Source

The problem, correctly identified by @RadLexus, is you're reopening the file every time you call addChunk.

File handles, file pointers, file numbers all work basically the same way: they all act like cursors in an editor. When you open a file for reading, the file handle is at the start. When you read from the file handle, the cursor moves through the file holding your place. When you close the file handle, the cursor is thrown out. When you open it again, it starts at the beginning of the file again.

Since you're reopening the file every time you call addChunk you're re-reading from the start of the file again. Your use of the global variable sString should have tipped you off that something was wrong. Globals are just about always a sign of a poorly designed function.

Instead, open the file outside of addChunk and pass in the file handle. This will fix the re-opening problem, and addChunk will be able to be used on other files without having to change a global variable and possibly mess up some other code.

#include <errno.h>
#include <string.h>

int fd = open(sString, O_RDONLY);
if( fd < 0 ) {
    fprintf(stderr, "Can't open '%s' for reading: %s\n", sString, strerror(errno));

/* Read two chunks into buffer */
addChunk(fdIn, buffer, size);
addChunk(fdIn, buffer, size);

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download