[英]Need help about binary files
我在創建一個創建包含多行的 bin 文件的代碼時遇到問題,每行包含每行 6 個值。 例如:我正在做一個小項目,其中每一行都是一個“密碼”,所以我的系統將加載這個文件並從中讀取所有密碼,當它被更新時等等。我還沒有實現讀取文件的方法但是因為我正在努力操作文件。 該項目將在具有 Raspberry pi 的 GPIO 功能的 Linux 上運行,因此我使用 Visual Studio 來創建主代碼。
我目前的代碼是:
#define _CRT_SECURE_NO_WARNINGS
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
char keys[4] = { '1', '2', '3', '4' }; // NOT USING
char temp_key[6];
int incl_key() {
int i;
FILE *fp;
char code = "0";
int control = 0;
int var_internal = 0;
fp = fopen("keys.bin", "wb");
if (fp == NULL) {
printf("\n Error opening file. \n");
}
printf("write your sequence <6 digits>:\n");
do{
scanf("%s", &temp_key);
fputs(temp_key, fp);
fputs("\n", fp);
control++;
} while (control < 5);
fclose(fp);
}
int keys_db() {
return 0;
}
int main() {
incl_key();
system("PAUSE");
}
提前致謝。
數組太小,用戶無法將其輸入為字符串。
char temp_key[6];
printf("write your sequence <6 digits>:\n");
scanf("%s", &temp_key); // poor code
字符串是由第一個空字符終止並包括第一個空字符的連續字符序列。
當一個類型1 , 2 , 3 , 4 , 5 , 6 , Enter時,將'1'
, '2'
, '3'
, '4'
, '5'
, '6'
, '\n'
放入stdin
。 scanf("%s", temp_key);
尋找前導空白,沒有看到,然后讀取 6 個非空白字符並將它們保存在temp_key[0]
、 temp_key[1]
、 .... temp_key[5]
中。 讀取'\n
'(一個空格), "%s"
指示停止掃描更多內容,將'\n'
放回標准輸入以供以后輸入,然后嘗試將空字符附加到stdin
temp_key[6]
使它成為一個字符串。 但是temp_key[]
太小了,所以任何事情都可能發生 - 這是未定義的行為。 其余代碼無關緊要。
scanf("%s", &temp_key);
不正確的代碼有 3 個原因。
&temp_key
當數組的第一個元素的地址需要匹配"%s"
時傳遞數組的地址。 這兩個地址具有相同的值,但類型不同。 這本身就是未定義的行為。 然而絕大多數時候,它像正確的scanf("%s", temp_key);
一樣“工作”。 (沒有&
)
scanf("%s", temp_key);
對讀取的數據量沒有限制,如上所述,輸入 6 位或更多位會導致緩沖區溢出和未定義的行為。
沒有檢查返回值,所以代碼不知道事情是否成功。 stdin
可能已關閉(不再輸入)或其他問題。
而是使用fgets()
讀取一行用戶輸入並將該輸入轉換為string 。
#define KEY_N 6
// key \n \0 extra - why be stingy?
char temp_key[KEY_N + 1 + 1 + 10];
//scanf("%s", &temp_key);
if (fgets(temp_key, sizeof temp_key, stdin)) {
// user input successfully read!
temp_key[strcspn(temp_key), "\n"] = '\0'; // lop off potential trailing \n
if (strlen(temp_key) != KEY_N) Handle_Invalid_Input();
else GoodToGo();
}
代碼也可能有其他問題。
例如:二進制與文本模式下的fp
以及“在 linux 上運行......所以我正在使用 Visual Studio”擔心讀取看起來像文本文件的“keys.bin”的期望。 目前,只要將其視為二進制文件,OP 正在做的事情看起來還不錯。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.