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 !
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 needsize_t nbytes = fread(buffer, 1, 512, infile);and check that you got a non-zero number of bytes read. - Jonathan Leffler