我解決了 CS50 中的 pset4 恢復問題。雖然我解決了這個問題,但我對“buffer”和“&buffer”感到困惑。請關注“LINE AAAA”和“LINE BBBBB”。
#include <stdio.h>
#include <stdlib.h>
#include <stdint.h>
// New type to store a byte of data
typedef uint8_t BYTE;
// Number of "block size" 512
const int BLOCK_SIZE = 512;
int main(int argc, char *argv[])
{
// Check for 2 command-line arguments
if (argc != 2)
{
printf("Usage: ./recover IMAGE\n");
return 1;
}
// Open card.raw file
FILE *input = fopen(argv[1],"r");
// Check for fail to open
if (input == NULL)
{
printf("Couldn't open the file.\n");
return 1;
}
// Read the first 4 bytes
BYTE buffer[BLOCK_SIZE];
// Count image
int count_image = 0;
// Assign NULL to output_file
FILE *output = NULL;
// Declare filename
char filename[8];
// LINE AAAAA
while (fread(buffer, sizeof(BYTE), BLOCK_SIZE, input) == BLOCK_SIZE)
{
// Check first 4 bytes for JPEG file format
if (buffer[0] == 0xff && buffer[1] == 0xd8 && buffer[2] == 0xff && (buffer[3] & 0xf0) == 0xe0)
{
// Only for first image, generate new filename and write into it
if (count_image == 0)
{
// Generate a new file with sequence name
sprintf(filename, "i.jpg", count_image);
// Open new file
output = fopen(filename, "w");
// LINE BBBBB
fwrite (&buffer, sizeof(BYTE), BLOCK_SIZE, output);
// Add filename counter
count_image ;
}
// For subsequence new repeat JPG images
// Close output file, generate new file, and write into it
else if (count_image > 0)
{
// fclose current writing files
fclose (output);
// Generate a new file with sequence name
sprintf(filename, "i.jpg", count_image);
// Open new file
output = fopen(filename, "w");
// LINE BBBBB
fwrite (&buffer, sizeof(BYTE), BLOCK_SIZE, output);
// Add filename counter
count_image ;
}
}
// Not fulfill the 4 bytes JPG condition, keep writing to the same filename
else if (count_image > 0)
{
// LINE BBBBB
fwrite (&buffer, sizeof(BYTE), BLOCK_SIZE, output);
}
}
fclose(output);
fclose(input);
}
問:為什么我們在LINE BBBBB中使用“&buffer”而不是“buffer”?
我知道 LINE AAAAA 正在使用“緩沖區”,因為 BYTE 緩沖區 [BLOCK_SIZE] 是指標或陣列。所以“緩沖區”是指指標的位置。
uj5u.com熱心網友回復:
使用buffer時,通常會轉換為第一個元素的地址。 &buffer是陣列的地址。
這兩個地址將比較相等,但具有不同的型別。當型別很重要時,請使用匹配的型別。啟用所有警告以幫助識別不正確的型別使用。
自fread()使用以來void *,任何一個都可以。
從概念上講buffer,在這種情況下使用來匹配sizeof(BYTE)and BLOCK_SIZE。
要么
fread(&buffer, sizeof buffer, 1, input) == 1)
uj5u.com熱心網友回復:
fwrite(buffer, ...) 可以正常作業。
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/448785.html
上一篇:將數字插入陣列
