我在線觀看了解決方案,但一個細節對我來說并不清楚,
哪個特定的命令列可以完成創建 jpg 檔案的作業?
我想除了 sprintf 沒有其他東西可以做到這一點,但它究竟是如何做到的呢?
據我所知,它 olny 將檔案名列印到位置但不創建它
int main(int argc, char *argv[])
{
FILE *raw_file = fopen(argv[1], "r");
if (raw_file == NULL)
{
printf("Could not open file");
return 1;
}
unsigned char buffer[512];
int count = 0;
FILE *output = NULL;
char *filename = malloc(8);
while (fread(buffer, 1, 512, raw_file) == 512)
{
if(buffer[0] == 0xff && buffer[1] == 0xd8 && buffer[2] == 0xff && (buffer[3] & 0xf0) == 0xe0)
{
sprintf(filename, "i.jpg", count);
output = fopen(filename, "w");
count ;
}
if (output != NULL)
{
fwrite(buffer, 1, 512, output);
}
}
free(filename);
fclose(output);
fclose(raw_file);
return 0;
}
uj5u.com熱心網友回復:
哪個特定的命令列可以創建 jpg 檔案?
通常我們稱這些為“[C] 代碼行”。術語“命令列”通常指的是作為在終端(或“控制臺”)上運行的整個程式的命令。實際上有兩行代碼負責在jpg這里創建檔案。第一個是:
output = fopen(filename, "w");
這將創建一個用于寫入的檔案。但此時它是空的,因為它不包含任何資料內容。filename只是要創建的檔案的名稱。對可以寫入資料的記憶體的參考由變數回傳fopen并分配給output變數。
檔案的內容寫在這一行:
fwrite(buffer, 1, 512, output);
其中要寫入的資料源由buffer變數給出。這指向從fread上面的原始檔案中讀取的資料。
我想除了 sprintf 沒有其他東西可以做到這一點,但它究竟是如何做到的呢?
這里sprintf只是寫一個檔案名,將其分配給變數filename。這些將是“000.jpg”、“001.jpg”、“002.jpg”等等。
'fwrite' 不會直接寫入磁盤,因為這會非常低效。而是將資料寫入緩沖存盤器(稱為stream)。為了確保流被重繪 到磁盤,呼叫了以下行(它可能應該在打開新的輸出檔案之前在回圈內呼叫):
fclose(output);
讀取原始檔案時,請注意對其內容進行了一些檢查:
if(buffer[0] == 0xff && buffer[1] == 0xd8 && buffer[2] == 0xff && (buffer[3] & 0xf0) == 0xe0)
0xFF 0xD8是“影像開始”JPEG 標記。此處用作確保/檢測源(原始)檔案段確實包含 JPEG 資料的一種方式。查看JPEG 維基百科頁面中的“通用 JPEG 標記”表。
建議在處理二進制資料時將'b'字符(表示“二進制”)添加到函式中,如注釋中所建議的那樣。fopen例如,如本fopen手冊中所述:
The mode string can also include the letter 'b' either as a last
character or as a character between the characters in any of the
two-character strings described above. This is strictly for
compatibility with C89 and has no effect; the 'b' is ignored on
all POSIX conforming systems, including Linux. (Other systems
may treat text files and binary files differently, and adding the
'b' may be a good idea if you do I/O to a binary file and expect
that your program may be ported to non-UNIX environments.)
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/506979.html
