I have an if condition and inside of the if condition I create a file and write to it. But naturally, I can't use the pointer outside of the condition. I'm new to C and I'm looking for a way to make that pointer global variable like in python. Here is my code:
//check the chunk if it is a JPEG by looking first 4byte of the chunk
if (chunk[0] == 0xff && chunk[1] == 0xd8 && chunk[2] == 0xff && (chunk[3] & 0xf0) == 0xe0)
{
nofjpeg++;
//create a temporary file name
char filename[8];
if (nofjpeg == 1)
{
//create a new file name
sprintf(filename, "%03i.jpg", nofjpeg);
//open the file in write mode
FILE *outptr = fopen(filename, "w");
if (outptr == NULL)
{
fprintf(stderr, "Could not open %s.\n", argv[1]);
return 2;
}
fwrite(&chunk, chunksize, 1, outptr);
}
else
{
//close the previous file
fclose(outptr);
//create a new file name
sprintf(filename, "%03i.jpg", nofjpeg);
//open the file in write mode
FILE *outptr = fopen(filename, "w");
if (outptr == NULL)
{
fprintf(stderr, "Could not open %s.\n", argv[1]);
return 2;
}
fwrite(&chunk, chunksize, 1, outptr);
}
}
else if(nofjpeg > 1)
{
fwrite(&chunk, chunksize, 1, outptr);
}
nofchunks--;
You can see that inside of the first inner if condition I open the file and write to it. And I need to close that file inside the following else condition. You can also see I also use that pointer following the outer if condition.
Aucun commentaire:
Enregistrer un commentaire