strncat
was made for strings. But &c
is not a string.
Also, the original buffer is never allocated, so its contents is undefined. You're lucky that the program didn't immediately crash.
Afer allocating a suitable buffer, you could use fgets
here, or keep reading the characters in, one by one. In this latter case, remember to add a terminating zero, as this is the C standard for strings. If you use fgets
, you'll read in also any line-terminating character ("\n"), and you might want to remove it.
Also, remember to close the files when you're through using them, or before exiting the function where the file pointer is defined - otherwise, system resources will leak.
For example:
FILE *shader;
char* realShader;
// Open the file, and check that opening succeeded.
if (NULL != (shader = fopen(shaderName, "r"))) {
// Allocate some memory for realShader, and check
// that the allocation did work.
if (NULL != (realShader = malloc(1024))) {
char *c;
// Read one line
if (NULL == fgets(realShader, 1024, shader)) {
// Read failed. No sense in keeping memory allocated
free(realShader); realShader = NULL;
} else {
// If there is a return at end of line...
c = strchr(realShader, '\n');
if (c) {
// ...kill it.
*c = 0;
}
}
}
fclose(shader); // shader = NULL;
}
return realShader;
UPDATE
If you want to read the whole file, then you need to know its size (unless you want to use realloc
in a cycle, also doable). For that, you would use the stat
function after temporarily allocating a buffer for the stat info:
// Create the structure on the stack as a temporary variable
// (no malloc)
struct stat statbuf;
fstat(shaderName, &statbuf);
// This is, in general, not a good idea because "st_size" is not
// necessarily what malloc expects. On my system it is a 64 bit
// value, and so is malloc's size_t, so things work. Otherwise a
// compiler warning is the least you can expect.
// (also, blindly loading large chunks of data into memory is
// not the first thing you should go for if at all avoidable).
realShader = malloc(statbuf.st_size);