开发者

File processing in c?

I have been given a raw file that holds several jpg images. I have开发者_开发百科 to go through the file, find each jpg image, and put those images each in a separate file. So far I have code that can find each where each image begins and ends. I also have written code that names several file names I can use to put the pictures in. It is an array: char filename[] , that holds the names: image00.jpg - image29.jpg .

What I cannot figure out is how to open a file every time I find an image, an then close that file and open a new one for the next image. Do I need to use fwrite()? Also, each image is in blocks of 512 bytes, so I only have to check for a new image every 512 bytes once I find the first one. Do I need to add that into fwrite?

So, to summarize my questions, I don't understand how to use fwrite(), if that is what I should be using to write to these files. Also, I do not know how to open the files using the names I have already created.

Thanks in advance for the help. Let me know if I need to post any other code.


  1. Use fopen(rawfilename, "rb"); to open the raw file for reading. and fread to read from it.
  2. Use fopen(outfilename, "wb"); to open output file for writing and fwrite to write to it.
  3. As mentioned in my comment, you are assigning char *[] to char*, use char filename[] = "image00.jpg"; instead.
  4. Don't forget to close each file after you finish its processing (r/w) (look at fclose() at the same site of other links)
  5. Decide how much bytes to read each time by parsing the jpeg header. Use malloc to allocate the amount of bytes needed to be read, and remember, for each allocation of buffer you need to free the allocated buffer later.


Pretty much any book on C programming should cover the functions you need. As MByD pointed out, you'll want to use the functions fopen(), fwrite(), and fclose().

I imagine your code may include fragments that look something like

/* Warning: untested and probably out-of-order code */
...
char **filename = {
    "image00.jpg", "image01.jpg", "image02.jpg",
    ...
    "image29.jpg" };
...
int index = 0;
const int blocksize = 512; /* bytes */
...
index++;
...
FILE * output_file = fopen( filename[index], "wb");
fwrite( output_data, 1, blocksize, output_file );
fclose(output_file);
...
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜