目前,作為練習,我正在使用 C 編程語言構建一個小型資料庫。資料庫將被構建為結構的集合。每個結構都包含特定元素(在本例中為 id、用戶名和密碼)。在下面的代碼中,我正在測驗在資料庫中寫入一個專案(只不過是一個檔案)。我遇到的唯一問題是檔案上寫入的實際字符,以及當我嘗試讀取檔案內容時,終端螢屏上沒有列印任何內容。
Here is the full code:
#include <fcntl.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
struct obj{
unsigned id;
char *username;
char *password;
};
struct obj new_dat_elem;
int main(){
int fd;
int n;
char buf[4096];
new_dat_elem.id = 0;
new_dat_elem.username = (char *)malloc(sizeof(char) strlen("Name") 1);
strcpy(new_dat_elem.username, "Name");
new_dat_elem.password = (char *)malloc(sizeof(char) strlen("Password") 1);
strcpy(new_dat_elem.username, "Password");
if((fd = open("database.txt", O_WRONLY | O_APPEND, 0)) != -1){
if((n = write(fd, &new_dat_elem, sizeof(new_dat_elem))) != -1){
printf("SUCCESS: %d bytes written of the file\n", n);
close(fd);
}
}
if((fd = open("database.txt", O_RDONLY, 0)) != -1){
if((n = read(fd, buf, sizeof(buf))) != -1){
write(0, buf, n);
}
}
}
1個程式運行后database.txt的內容:
·
·
有人可以解釋一下這些字符是什么以及為什么將它們寫在檔案上嗎?即使是十六進制轉儲資料庫檔案,這些值也沒有任何意義。此外,我想也許代碼的最后一部分螢屏上沒有顯示任何內容取決于這個問題......提前致謝。
uj5u.com熱心網友回復:
當您寫出此檔案時,您希望檔案中包含什么
struct obj{
unsigned id;
char *username;
char *password;
};
你期待嗎
42, dave, magic
這不會發生,而是你會得到一串位元組(大小取決于你的計算機)
xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
value of id ........
value of name ptr ................
value of password ptr ................
您可以看到,如果您od在 linux 上使用或在 windows 上使用類似 hxd 的檔案對檔案進行十六進制轉儲。
如果你想要文本,你必須做一些完全不同的事情。
順便說一句,您可能沒有得到我所說的輸出,因為您從未測驗任何 IO 操作是否有效,但是一旦您使它們正常作業,那么這就是您將得到的
特別注意這些字串沒有寫出
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/446356.html
標籤:C file structure low-level write
上一篇:如何讓它在同一行列印輸出?
