Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

How to overwrite a file with less content #2203

Open
sphaero opened this issue Nov 15, 2021 · 3 comments
Open

How to overwrite a file with less content #2203

sphaero opened this issue Nov 15, 2021 · 3 comments

Comments

@sphaero
Copy link
Contributor

sphaero commented Nov 15, 2021

It seems it updates the file in place leaving the old content in the tail.

zfile_output calls fopen (self->fullname, "r+b"); which according to docs:

r+ or rb+ or r+b: Open file for update (reading and writing).

To write the new file without a tail of old data we'd need:

w+ or wb+ or w+b
Truncate to zero length or create file for update.

However the old behaviour is probably also needed? Perhaps we need to add another method like zfile_output_truncate ?

@sphaero
Copy link
Contributor Author

sphaero commented Nov 16, 2021

A fix could be something like this:

                    ssize_t oldSize = zfile_size(zfile_filename(file, NULL));
                    int rc = zfile_output(file);
                    if (rc == 0) {
                        zchunk_t* data = zchunk_frommem(text, strlen(text), nullptr, nullptr);
                        int rc = zfile_write(file, data, 0);
                        if (oldSize > strlen(text) )
                        {
#ifdef __WINDOWS__          // truncate the file
                            if ( _chsize_s(fileno(zfile_handle(current_editor->file)), (__int64)strlen(text)) != 0 )
                            {
                                zsys_error("Some error trying to truncate the file");
                            }
#else
                            ftruncate(fileno(zfile_handle(current_editor->file)), strlen(text));
#endif
                        }
                        zfile_close(current_editor->file);

@stale
Copy link

stale bot commented Apr 16, 2022

This issue has been automatically marked as stale because it has not had recent activity for 90 days. It will be closed if no further activity occurs within 21 days. Thank you for your contributions.

@stale stale bot added the stale label Apr 16, 2022
@sphaero
Copy link
Contributor Author

sphaero commented May 19, 2022

Don't closeas this needs fixin or proper instructions

@stale stale bot removed the stale label May 19, 2022
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant