P.S. 「コードを改善する」という質問を理解している人がいました。私はそれをもっと明確にすることはできませんでした。私はその間にこの問題を解決しました。コピーペーストを削除するためのCコードの改善
私はcdカードファイル(.raw)から写真を復元する作業に取り組んでいます。まず、それらを「マジックナンバー」で検索します。もし誰かがそれを知っていれば、それはCS50クラスの一部です。
とにかく、ok-ishで動作するようです。私はすべての写真を取り戻すことができますが、品質の悪いものもあれば、白い画素がたくさんあるものもあります。
条件に応じてコードにjpgファイルを開いて閉じます。コピー貼り付けを避けてファイルをfopen、fwrite、fcloseする方法を理解できません。私はこの部分を改善したいと思います。コードは次のとおりです。
typedef uint8_t BYTE;
int main(void)
{
// open input file
FILE* card_file = fopen("card.raw", "r");
if (card_file == NULL)
{
printf("Could not open card.raw\n");
return 1;
}
// declare output file
FILE* image;
// array to store values we read for each 512 bytes
BYTE buffer[512];
// number of jpg files found
int jpgs = 0;
// variable used to create new files
char title[10];
// execute until the end of file is reached
while(fread(&buffer, sizeof(BYTE), 512, card_file) > 0)
{
// find a new jpg file by its magic numbers
if((buffer[0] == 0xff) && (buffer[1] == 0xd8) && (buffer[2] == 0xff))
{
//create a new file if it's found
sprintf(title, "%03d.jpg", jpgs);
jpgs++;
//open the file and check if file is opened correctly
image = fopen(title, "a");
if (image == NULL)
{
fprintf(stderr, "Could not create %03d.jpg\n", jpgs);
return 2;
}
// write into the file and close it
fwrite(&buffer, sizeof(BYTE), 512, image);
fclose(image);
}
else
{
//check if a jpg file was already found before
if(jpgs > 0)
{
//open the file and check if file is opened correctly
image = fopen(title, "a");
if (image == NULL)
{
fprintf(stderr, "Could not create %03d.jpg\n", jpgs);
return 2;
}
// write into the file and close it
fwrite(&buffer, sizeof(BYTE), 512, image);
fclose(image);
}
}
}
//close the input file
fclose(card_file);
}
私は別の関数を作成しようとしましたが、渡す必要のある整数値へのポインタを処理する方法がわかりませんでした。
ご協力いただければ幸いです。
を理由だけではなく、あなたが渡す機能(に入れませんバッファとファイル名に)? – Dmitri
コピー・ペーストはエディタの問題です。それはCとどのように関連していますか?あなたの質問は明確ではありません。コードを再利用するには、機能の学習を開始してください。 – Olaf
こんにちはOlaf、コピー貼り付けは私のプログラムにいくつかのコードをコピーして貼り付ける必要がある場合は、それを行うより良い方法があるということです。私は自分のコードを改善したかっただけです。 –