error checking fread wrapper

I'm working on a large project, trying to eliminate warnings. One of the most common warnings that crops up is that the return value from fread isn't checked. fread and kin are used so ubiquitously it would be unwise for me to go through and convert all the files to a c++ stream idiom at this point.

To work around the warnings, I've written an fread wrapper that checks that the return value is correct:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
// Write an error message and exit
void error(string message)
{
	cout << message << endl;
	exit(-1);
}

// Error-checking fread wrapper function
size_t fileRead(void* ptr, size_t size, size_t count, FILE* stream)
{
	size_t returnCount = fread(ptr, size, count, stream);
	if (returnCount != count)
		error("Did not read the correct number of fields");
}

This works in most cases but I've run into a hitch.

While linking I get this error:

undefined reference to `fileRead(void*, unsigned long, unsigned long, _IO_FILE*)'

The error comes up on calls of the following form:

1
2
unsigned char type;
fileRead(&type, 1, sizeof(unsigned char), fp);


What is happening?
Sounds like you are not linking your fread wrapper cpp with the rest of your project.

EDIT: Added a "not".
Last edited on
Could the fact that I'm calling the wrapper from within a namespace cause this error? In some files it links correctly and in others it does not so I'm wondering if that could be the problem.
Thanks, the problem was a completely unrelated issue. I hadn't told cmake to link the executable against my new folder.

If anyone is interested, these are the two wrappers I ended up using:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
// Error-checking fread wrapper function
size_t freadSafely(void* ptr, size_t size, size_t count, FILE* stream)
{
	size_t returnCount = fread(ptr, size, count, stream);
	if (returnCount != count)
		error("Did not read the correct number of fields");
}

// Error-checking fgets wrapper function
char* fgetsSafely(char* str, int num, FILE* stream)
{
	char* temp = fgets(str, num, stream);
	if(temp==NULL)
	{
		if(ferror(stream))
			error("fgets returned an error!");
		else
			error("fgets hit EOF!");
	}
	return temp;
}
Topic archived. No new replies allowed.