user3214998
user3214998

Reputation:

Troubles appending structure to file in C

I'm having some trouble to append a structure to a file: OS: Ubuntu 14.04

Struct:

struct baris
{
    char name[30];
    char trusted[1];
    int phone;
    int id;
};

Func:

addNewBariga()
{
    char answer[30];
    struct baris new;
    while(1){
        printf("Enter new Barigas' ID please.");
        scanf("%d",&new.id);
        printf("Enter new Barigas' name please.\n");
        scanf("%s",new.name);
        printf("Enter new Barigas phone please. \n");
        scanf("%d", &new.phone);
        printf("Is Bariga trusted?\n\t[Y/N]:");
        scanf("%s",new.trusted);
        while(1)
        {
            if(strcmp(new.trusted,"Y") != 0 && strcmp(new.trusted,"y")  != 0)
            {
                printf("%s",new.trusted);
                printf("\nWrong command givven.\t\n[Y/N]:");
                scanf("%s",&new.trusted);
            }
            else
                break;
        }
        printf("Values you've entered:\n\tID:%d\n\tName: %s\n\tPhone: %d\n\tTrustworth:%s\nWould you like to proceed to saving?\n[Y/N]:\n",new.id,new.name,new.phone,new.trusted);
        scanf("%s",&answer);
        if(strcmp(answer,"Y") ==0 || strcmp(answer,"y")==0) //Process to saving
        {
            printf("saving...");
            confPtr = fopen(filePath , "ab");
            //fwrite(new.id, sizeof(new.id), 1, confPtr);
            fwrite(&new, sizeof(struct baris), 1, confPtr);
            fclose(confPtr);
            break;
        }
}

What I'm getting:

fabio\00\00\00\00\00\00\00\00\00fab\00\00\00\00\00\00\00\00\00fab\00\00\00\00\00\00\00\00\00\00\00\00\00\00\00\00\00\00\00\00\00 <1\B5y\00\00\00\00\00\00\00fab\00\00\00\00\00\00\00\00\00\00\00\00\00\00\00\00\00\00\00\00\00 \C5f\DAy\00\00\00\00\00\00\00

Upvotes: 0

Views: 581

Answers (1)

unwind
unwind

Reputation: 399753

That output looks basically correct, what did you expect?

You're writing binary data to a binary file. Binary files are not very easy to inspect manually.

The first member of the structure, name, will always be 30 bytes long in the output for example.

Note as pointed out by @BLUEPIXY in a comment that this:

scanf("%s",new.trusted);

triggers undefined behavior if a non-zero length is entered, since trusted is only 1 character long that is consumed by the string terminator. You should increase its length, or (much better!) stop using direct scanf() like this and instead read a whole line of input with fgets() and parse it using sscanf().

Also, when using functions that can fail (like scanf(), sscanf() or fgets()) you must check the return values before relying on them to have succeeded.

Upvotes: 1

Related Questions