I’m trying to read a file in C, but after writing a bunch of code in order to allocate memory I’m having problems actually reading the file in that I’m getting a memory access violation, I tried allocating more memory than I actually need for the char pointer but ultimately I’m still getting the memory allocation error, the code is currently
static char* readShader(char path[]) {
char cwd[1024];
if (getcwd(cwd, sizeof(cwd)) != NULL) {
printf("Current working dir: %s\n", cwd);
}
else {
perror("getcwd() error");
}
int lines = 0;
char full_path[512];
snprintf(full_path, sizeof(full_path), "%s/%s", cwd, path);
FILE* fpointer = fopen(full_path, "r");
if (fpointer == NULL)
{
printf("ERROR: COULD NOT LOAD SHADER");
return NULL;
}
int ch;
lines++;
while ((ch = fgetc(fpointer)) != EOF) {
if (ch == '\n') {
lines++;
printf("reading line: %d \n", lines);
}
}
printf("there are %d ", lines);
printf("lines in the file %s\n", path);
rewind(fpointer);
fseek(fpointer, 0, SEEK_END); // Move to the end of the file
int fileSize = ftell(fpointer); // Get the size of the file
rewind(fpointer);
printf("filesize: %d\n", fileSize);
char* shaderCode = malloc(fileSize);
if (shaderCode == NULL) {
printf("Memory allocation failed\n");
fclose(fpointer);
return NULL;
}
char* str = malloc(fileSize + 1);
if (str == NULL)
{
printf("Memory allocation failed\n");
fclose(fpointer);
return NULL;
}
while (fgets(str, fileSize, fpointer) != NULL) // fgets() will return NULL on EOF
{
printf("%s", str);
}
printf("%s", str);
printf("\n");
fclose(fpointer);
printf("Shader loaded successfully. File size: %ld bytes\n", fileSize);
return shaderCode;
}
with the error happening at
while (fgets(str, fileSize, fpointer) != NULL)
You need to sign in to view this answers
Leave feedback about this