0
votes

I'm having trouble with my following C code :

int main(void){

    FILE* infile = fopen("file","r);
    FILE* fp = NULL;

    unsigned char* buffer = malloc(512);

    while( fread(buffer,512,1,infile) > 0 ){ //reading a file block by block

           if(buffer[0] == 0xff){
               ... //defining variable "name"
               if(fp != NULL)fclose(fp);
               fp = fopen(name,"w+");
               fwrite(buffer,512,1,fp);
           } else if(fp != NULL) {
                   fwrite(buffer,512,1,fp);
           }

    }

}

It seems that i can't fopen after fclose using the same pointer, why ? I need my pointer to remain accessible everywhere in the main so i can't declare a new one in my while.

EDIT: Oh god, problem solved. I was probably super tired. I was compiling the wrong file. Anyway...

Thanks, folks !

1
You aren't 'using' the same pointer there. You're just capturing a return value. The segfault is caused by code that you haven't posted here. - Ron Dahlgren
I know this is strange, but if i don't free memory with flose(fp), sgefault does not occurs anymore. - superzamp
Please construct the smallest complete program that recreates the problem. - Oliver Charlesworth
Here, i edited my code. Thanks for your answers guys. - superzamp
Note that fread(buffer, 512, 1, infile) will return 0 or 1, depending on whether it reads 512 bytes or not. If you want to read 512 byte blocks only, that's fine. If you want to read up to 512 bytes at a time, then you need size_t nbytes = fread(buffer, 1, 512, infile); and check that you got a non-zero number of bytes read. - Jonathan Leffler

1 Answers

1
votes

It's hard to tell why since you aren't showing us all of your code. However, reopening the file should be pretty straightforward:

#include <stdio.h>

int main(void)
{
  FILE* fp = NULL;
  char name[] = "somefile";

  for (;;)
  {
    // do something
    if ((fp = fopen(name, "w+")) == NULL)
      break;
    // do something with the file
    fclose(fp);
    // do something
  }

  return 0;
}