我想撰寫一個代碼來計算檔案中特定十六進制數字的出現次數。例如在檔案中有0x01 0x02 0x03 0x41 0x42 0x43 0x0D 0x0A 0xFF 0xFE 0xFD 0x01 0x02 0x03 0x80 0x7F 0x0D 0x0A,如果我輸入:FF它將輸出:1
我已經在處理代碼,但它似乎不起作用
#include <stdio.h>
#include <stdlib.h>
main ()
{
FILE *in, *out;
unsigned char a[1000] = { 0 };
int b;
int count = 0, i = 0;
in = fopen ("a.dat", "rb");
out = fopen ("b.txt", "wb");
while (!feof (in)) {
b = fgetc (in);
a[i] = b;
i ;
}
scanf ("%x", &b);
for (i = 0; i < 1000; i ) {
if (a[i] == b) {
count ;
}
}
fprintf (out, "%d\n", count);
printf ("%d\n", count);
fclose (out);
fclose (in);
return 0;
}
(注意:'}'固定的嵌套錯誤)
uj5u.com熱心網友回復:
你有大量的小錯誤。它們可以總結如下:
while (!feof(in))讀取一個字符太多。看看回圈的邏輯。讀完最后一個字符后,您檢查!feof(in)(尚未發生)然后b = fgetc (in);再次呼叫(現在回傳EOF),然后您盲目地分配a[i] = b;. 這就是為什么 while ( !feof (file) ) 總是錯誤的?只需通過讀取函式的回傳來控制您的讀取回圈。- 您使用了錯誤的型別
scanf()。%x需要一個unsigned int*值,但你傳遞 typeint*。這將導致有符號和無符號型別不匹配的問題。當您在啟用警告的情況下進行編譯時,這一點很明顯。 - 您無法驗證您是否打開
in并out成功。始終驗證每個檔案打開操作。 - 您無法驗證
scanf().scanf()除非您驗證回傳的數字等于預期的有效轉換次數,否則您無法正確使用。 - 既然你寫信給你,
b.txt你應該驗證fclose(out). 始終驗證您的close-after-write以確保您捕獲在您的代碼寫入最后一個值之后發生的任何寫入錯誤。 - 無需遍歷
1000陣列的所有元素。您知道從 的值填充的元素數量i。只需回圈使用單獨的回圈變數填充的元素(j如下所示)。 - 最后,當您需要用戶輸入時,不要讓用戶盯著螢屏上閃爍的游標想知道程式是否掛起或發生了什么,提示用戶輸入。
將所有部分放在一起,您可以執行類似以下的操作:
#include <stdio.h>
#include <stdlib.h>
#define MAXC 1000 /* if you need a constant, #define one (or more) */
int main (void)
{
FILE *in, *out;
unsigned char a[MAXC] = { 0 };
int b;
unsigned u; /* unsigned value required for scanf() */
int count = 0, i = 0, j;
in = fopen ("a.dat", "rb");
out = fopen ("b.txt", "wb");
if (!in) { /* always validate every file open */
perror ("fopen-a.dat");
return 1;
}
if (!out) { /* always validate every file open */
perror ("fopen-b.txt");
return 1;
}
/* protect array bound - use read function to control loop */
while (i < MAXC && (b = fgetc (in)) != EOF) {
a[i] = b;
i ;
}
fputs ("enter 8-bit hex value to find: ", stdout);
if (scanf ("%x", &u) != 1) { /* validte every user-input */
fputs ("error: invalid hex input.\n", stderr);
return 1;
}
for (j = 0; j < i; j ) { /* iterate over values read from file */
if (a[j] == u) {
count ;
}
}
fprintf (out, "%d\n", count);
printf ("%d\n", count);
if (fclose (out) == EOF) { /* always validate close-after-write */
perror ("fclose-out");
}
fclose (in);
}
示例使用/輸出
在啟用完整警告的情況下編譯代碼,您可以執行以下操作:
$ gcc -Wall -Wextra -pedantic -Wshadow -std=c11 -O3 -o bin/readwriteucbin readwriteucbin.c
如果你會得到,在二進制輸入上運行你的代碼,例如
$ ./bin/readwriteucbin
enter 8-bit hex value to find: 0xff
1
或者匹配多個值的情況,例如
$ ./bin/readwriteucbin
enter 8-bit hex value to find: 1
2
轉載請註明出處,本文鏈接:https://www.uj5u.com/qianduan/487788.html
標籤:C
下一篇:靜態修飾符如何在C中作業?
