Bla*_*Cat 1 c linux file-io system-calls
该文件仅包含相同类型的结构(mydata).
我试过这个:
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);
Run Code Online (Sandbox Code Playgroud)
我必须使用linux系统调用(http://codewiki.wikidot.com/system-calls)因为这是目标.
我尝试了很多方法,但我找不到只有这个的工作方案:
在临时文件中写入除最后一个mydata之外的所有内容,并使用O_TRUNC oflag重新打开原始文件并将内容写回.
你能告诉我这样做的正确解决方案是什么?
对于Linux,特别是ftruncate()需要文件描述符和需要文件路径的truncate().您需要做的就是确定文件应该有多少字节长度,然后调用其中一个字节.
我建议您首先确保文件大小是所需数据大小的倍数,以确保它可以被截断并且最后仍包含完整的数据项.
当初始文件大小小于一个数据项的大小或零时,或者不是数据项长度的倍数(以字节为单位)时,您可能还需要考虑如何处理极端情况.