Frage

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 !

War es hilfreich?

Lösung

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;
}
Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top