Delete data at end of file

T

The Doctor

Hi,

Is it possible to delete data at the end of a file?

I am using read(), write(), open() and so, but I didn't find a function
for deleteing data at the end of the file. Or is it enough to write the
EOF at the end of the data?

Grtz,
Leon
 
T

The Doctor

Since you are using low level function, you are reading binary files,
How may bytes do you have to delete from the end of the file?

sth like: Read till a point you know that the delete point is reached
and write it to a new file

ifstream file(filename, ios::in | ios::binary); if(file.is_open())
ifstream::pos_type sz;
// get file size
sz = file.tellg()
...
at this point you have an idea of the file size, and I suppose you also
have an idea about the portion to be deleted. You can write the portion
of the file until the deleted byte to another file. Can you post some
code and a minimal file?

Best

I determine the filesize by seeking to the end of the file with lseek(fd,
0, SEEK_END). The lseek then returns the size of the file (the offset
measured from the beginning of the file until the end of it).

Example code:

#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <unistd.h>
#include <string.h>

int main()
{
int fd = open("file.txt", O_CREAT | O_RDWR);

write(fd, "Hello, world!", strlen("Hello, world!")+1);

lseek(fd, 5, SEEK_SET);
// Delete from here, so the file becomes: "Hello"

close(fd);
}
 
D

Default User

The Doctor wrote:

Example code:

#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <unistd.h>
#include <string.h>


This is all non-standard (non-standard C++ that is). For POSIX
questions, the best place to ask is comp.unix.programmer.




Brian
 
S

Stefan Ram

utab said:
ifstream file(filename, ios::in | ios::binary);
if(file.is_open())
ifstream::pos_type sz;
// get file size
sz = file.tellg()
...
at this point you have an idea of the file size

In ISO/IEC 9899:1990:

»A binary stream need not meaningfully support
fseek calls with a whence value of SEEK_END.«

In ISO/IEC 14882:2003(E), »seekg« and »tellg« seem to be
defined using »pubseekoff«, which seems to be based on
»seekoff«, which seems to be based on »::std::fseek«,
for which the above quotation from ISO/IEC 9899:1990 applies.
 
D

Default User

Default said:
The Doctor wrote:




This is all non-standard (non-standard C++ that is). For POSIX
questions, the best place to ask is comp.unix.programmer.

Ah, not string.h, of course.





Brian
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
474,164
Messages
2,570,898
Members
47,439
Latest member
shasuze

Latest Threads

Top