Home > Software design >  Undefined chars wrote by low-level function write() on a file
Undefined chars wrote by low-level function write() on a file

Time:03-20

Currently, as exercise, I am building a small database using C programming Language. The database will be structured as a collection of structures. Each structure contain specific elements (in this case id, username and password). In the following code I am testing writing an item inside the database(which is no more than a file). The only problems I am experiencing are the actual chars written on the file and the fact that when I try to read the contend of the file nothing is printed on the terminal screen.

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);
        }
    }
}

Content of database.txt after 1 program run:

    
· 
· 

Can someone please explain me what this chars are and why they are written on the file? Even hex dumping the database-file, the values makes no sense. Furthermore, I suppose that maybe the fact that nothing is shown on screen in the last part of the code depend on this problem... Thanks in advance.

CodePudding user response:

What are you expecting to be in the file when you write this out

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

do you expect

 42, dave, magic

That wont happen, instead you will get a string of bytes (size depends on your computer)

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

You can see that if you do a hex dump of the file using od on linux or something like hxd on windows.

If you want the text you have to do something completely different.

BTW you might not be getting the output I say since you are never testing that any of the IO operations work, but once you make them work correctly then this is what you will get

In particular note that those strings are not written out

  • Related