So I'm doing this homework where I have to go through a memory card and recover some images by putting data into a buffer, creating new JPEG files from that buffer data and then writing that data into those new files to get the images. Right now, I'm stuck on how to open the newly created files using the fopen function in C in order to write that data, and each file is named, "###.jpg", incrementing up from 000.jpg to 050.jpg. I could just open and write the files over and over I guess, but that's obviously instinctively way wrong.
Below is a rough snippet of code to explain my problem. Not really worried about memory allocation or segmentation faults/errors just yet while writing this, I'm just trying to convey my idea so you all understand my problem. I tried putting file_num at the end parameter of fopen after "w", but that just got an error.
#include <stdio.h>
#include <stdlib.h>
const BLOCK_SIZE = 512;
int buffer[BLOCK_SIZE];
unsigned int file_num = 0;
int main()
{
//Open memory card
FILE *pFile = fopen(card.raw, "r");
//Open and create JPEG files
while(fread(buffer, 1, BLOCK_SIZE, pFile) == BLOCK_SIZE)
{
if(some condition)
{
//Create JPEG file
sprintf(pFile, "%.03i.jpg", file_num++);
//Open new JPEG files to write data(this is my problem right here)
FILE *pImg = fopen(###.jpg, "w");
....
}
}
}
You need a character buffer to store the string that
sprintfcreates. This string is used as the first argument tofopen.The
printfformat specifier forunsigned intis%u, not%i.Here is a simple example that creates the files 000.jpg up to, and including, 050.jpg.
It also writes the name of each file to the respective file (enclosed in
< >).In use: