简体   繁体   中英

How to delete the last data in a file with linux system calls in C?

the file contains only structs of the same kind (mydata).

I tried this:

int counter,file;
file = open(filename, O_RDWR, S_IRUSR | S_IWUSR);
// some error handling

// let's go to the end of the file
while(read(file,&mydata,sizeof(mydata))>0) counter++;
// let's go one step back
lseek(file,-sizeof(mydata),SEEK_CUR);
// delete the last data
write(file,NULL,sizeof(obs)); // it's not working :(

close(file);

I have to use linux system calls ( http://codewiki.wikidot.com/system-calls ) because that's the objective.

I tried many method but I cant find a working solution only this one:

Write everything except the last mydata in a temporary file, and reopen the original file with O_TRUNC oflag and write the content back.

Could you tell me what is the right solution to do this?

For linux specifically there is ftruncate() that requires a file descriptor and truncate() that requires a file path. All you need to do is decide how many bytes long your file should be, then call one of them.

I suggest you first make sure the file size is a multiple of your desired data size, to ensure that it can be truncated and still contain a full data item at the end.

You may also want to consider how to handle the corner cases, when initial file size is less than the size of one data item, or zero, or not a multiple of the size of your data item length in bytes.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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