繁体   English   中英

低级 function write() 在文件上写入的未定义字符

[英]Undefined chars wrote by low-level function write() on a file

目前,作为练习,我正在使用 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 的内容:

    
· 
· 

有人可以解释一下这些字符是什么以及为什么将它们写在文件上吗? 即使十六进制转储数据库文件,这些值也没有意义。 此外,我想也许在代码的最后一部分屏幕上没有显示任何东西这一事实取决于这个问题......提前致谢。

当你把它写出来时,你希望文件中有什么

   struct obj{
       unsigned id;
       char *username;
       char *password;
    };

你期待吗

 42, dave, magic

这不会发生,相反你会得到一串字节(大小取决于你的电脑)

             xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
 value of id ........
 value of name ptr   ................
 value of password ptr               ................

你可以看到,如果你在 linux 上使用od或在 windows 上使用 hxd 之类的东西对文件进行十六进制转储。

如果你想要文本,你必须做一些完全不同的事情。

顺便说一句,你可能没有得到我说的 output,因为你从来没有测试过任何 IO 操作是否有效,但是一旦你让它们正常工作,你就会得到

特别注意那些字符串没有写出来

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM