I would like to append to my record to a binary file, using linux system calls. Im a total beginnner in linux, and even in C.

So far i got:

int file;

struct rec new_record=addNewEntry(); 

file=open("mydatabase.db",O_APPEND  | O_CREAT);  

if (file<0)
{
    printf("Error at opening the file\n");
    return 1;
}

if (write(file, &new_record, sizeof(new_record)) < 0){
    printf("Writing error\n");
    return 1;
}

close(file);

my record struct and addNewEntry function:

struct rec addNewEntry(){

//init
char name[32];
char team[32];
char city[32];
char date[32];
int max;
int cost;

//input
printf("Type name: \n");
scanf("%s" , name);

printf("Type team: \n");
scanf("%s" , team);

printf("Type city: \n");
scanf("%s" , city) ;

printf("Type date: \n");
scanf("%s" , date);

printf("Type guests limit: \n");
scanf("%d", &max);

printf("Type price: \n");
scanf("%d", &cost);

//create record
struct rec record;

strncpy(record.name, name, 32);
strncpy(record.team, team, 32);
strncpy(record.date, date, 32);
strncpy(record.city, city, 32);

record.max = max;
record.cost = cost;

return record;
}

struct rec
{     

    int max,cost; 
    char name[32];
    char team[32];
    char city[32];
    char date[32];
}; 

Program exits with "Writing error". Any advice ? How could i dig deeper in this issue?

有帮助吗?

解决方案

Quoting the man page for open():

The argument flags must include one of the following access modes: O_RDONLY, O_WRONLY, or O_RDWR. These request opening the file read-only, write-only, or read/write, respectively.

Which your open call clearly doesn't follow. So add O_WRONLY or O_RDWR to your options.

其他提示

int t = open("test1.txt", O_WRONLY | O_APPEND);

use this mode it will append to the end of the file;

EXAMPLE CODE : //before that make sure file is created.

int main()
{
    int t = open("test1.txt", O_WRONLY | O_APPEND);
    char avd[100];
    printf("ENTER THE DATA - ");
    scanf("%s",avd);
    write(t,avd,12);
    close(t);
}
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top