How do I open individual files that increment up?

73 Views Asked by At

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");

            ....
        }
    }
}
1

There are 1 best solutions below

0
Oka On

You need a character buffer to store the string that sprintf creates. This string is used as the first argument to fopen.

The printf format specifier for unsigned int is %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 < >).

#include <stdio.h>
#include <stdlib.h>

int main(void)
{
    char file_name[64];

    for (unsigned n = 0; n <= 50; n++) {
        sprintf(file_name, "%03u.jpg", n);

        FILE *current_file = fopen(file_name, "w");

        if (current_file) {
            fprintf(current_file, "<%s>\n", file_name);
            fclose(current_file);
        }
    }
}

In use:

$ ./create_files
$ ls
000.jpg  007.jpg  014.jpg  021.jpg  028.jpg  035.jpg  042.jpg  049.jpg
001.jpg  008.jpg  015.jpg  022.jpg  029.jpg  036.jpg  043.jpg  050.jpg
002.jpg  009.jpg  016.jpg  023.jpg  030.jpg  037.jpg  044.jpg  create_files
003.jpg  010.jpg  017.jpg  024.jpg  031.jpg  038.jpg  045.jpg  create_files.c
004.jpg  011.jpg  018.jpg  025.jpg  032.jpg  039.jpg  046.jpg
005.jpg  012.jpg  019.jpg  026.jpg  033.jpg  040.jpg  047.jpg
006.jpg  013.jpg  020.jpg  027.jpg  034.jpg  041.jpg  048.jpg
$ cat 000.jpg 040.jpg
<000.jpg>
<040.jpg>
$ rm {000..050}.jpg