use fprintf (for string) or fwrite (for binary) to write data to file. use append mode ("a" or "ab") file opening to add data to an existing file (at the end). Answer from Deleted User on reddit.com
๐ŸŒ
Reddit
reddit.com โ€บ r/c_programming โ€บ how can i write to a file without overwriting?
r/C_Programming on Reddit: How can I write to a file without overwriting?
November 29, 2018 -

Hey, so I haven't really got this properly yet, however I've managed to create a read file function which works. I did write some code but I can't seem to get it to write on different occasions without writing a file. E.g. I have a struct with employee info. I want to enter: id, timestamp, name, job role, yadayada. But if I use:

fPointer = open("file.txt", "w");

printf("Enter entry\n> ");

scanf(" %s", UserInput);

fscanf(fPointer, "CUSTOM ENTRY WHICH I WANT THE USER TO INPUT", UserInput);

This doesn't create a file or write to one. This is all I have. Any suggestions?

๐ŸŒ
The Coding College
thecodingcollege.com โ€บ home โ€บ c write to files
C Write To Files - The Coding College
May 17, 2025 - #include <stdio.h> int main() { ... return 0; } ... To add data to an existing file without overwriting it, open the file in append mode ("a")....
Discussions

c++ - Writing into a text file without overwriting it - Stack Overflow
I'm doing a numerical simulation of gravity in C++ and I want to back up my results every time a single step is counted. However, the way I do it now, the programm always overwrites the file. I gu... More on stackoverflow.com
๐ŸŒ stackoverflow.com
C function to insert text at particular location in file without over-writing the existing text - Stack Overflow
I have written a program which takes a file as input and whenever it finds a line with length > 80, it adds \ and \n to that file to make it 80 chars in width max. The problem is that I have used ... More on stackoverflow.com
๐ŸŒ stackoverflow.com
C write in the middle of a binary file without overwriting any existing content - Stack Overflow
Today's problem is that I need to write an array of numbers in a binary file at a starting position. I have the position where it should start, and I don't want to overwrite values after that, just... More on stackoverflow.com
๐ŸŒ stackoverflow.com
How to output to a text file, without overwriting what was already on it?
When you call myText.open, you need to specify that you will open it in append mode rather than override mode. This can be done as so: myText.open("text.txt", std::ios_base::app); More on reddit.com
๐ŸŒ r/cpp_questions
3
5
July 16, 2020
๐ŸŒ
Academic Help
academichelp.net โ€บ coding โ€บ c-coding โ€บ write-to-a-file.html
How to Write to a File in C | AcademicHelp.net
January 13, 2024 - Additionally, fopen() allows you ... overwriting existing content in a file when writing in C, you should use the append mode (โ€œaโ€) in fopen()....
๐ŸŒ
Delft Stack
delftstack.com โ€บ home โ€บ howto โ€บ write to file in c
How to Write to File in C | Delft Stack
March 11, 2025 - You can easily adjust the loopโ€™s ... an existing file without overwriting its current contents, you can use the append mode (โ€œaโ€) when opening the file....
๐ŸŒ
Cprogramming
cboard.cprogramming.com โ€บ cplusplus-programming โ€บ 15065-writing-file-without-overwriting.html
Writing to a file without overwriting
April 10, 2002 - ofstream fout("c:/My Documents/TextFile.txt", ios::app); in this example whatever you want to add to a file will be inserted after the last item in a file thus no items will be overwritten..... Good Luck matheo917 ... I need to write to the middle of the file though, so i'm using ios::ate.
Find elsewhere
๐ŸŒ
W3Schools
w3schools.com โ€บ c โ€บ c_files_write.php
C Write To Files
Note: If you write to a file that ... ... If you want to add content to a file without deleting the old content, you can use the a mode....
Top answer
1 of 5
29

While there are a couple of techniques to do it in-place, you're working with a text file and want to perform insertions. Operating systems typically don't support text file insertions as a file system primitive and there's no reason they should do that.

The best way to do that kind of thing is to open your file for reading, open a new file for writing, copy the part of the file before the insertion point, insert the data, copy the rest, and then move the new file over the old one.

This is a common technique and it has a purpose. If anything goes wrong (e.g. with your system), you still have the original file and can repeat the transaction later. If you start two instances of the process and use a specific pattern, the second instance is able to detect that the transaction has already been started. With exclusive file access, it can even detect whether the transaction was interrupted or is still running.

That way is much less error prone than any of the techniques performed directly on the original file and is used by all of those traditional tools like sed even if you ask them to work in-place (sed -i). Another bonus is that you can always rename the original file to one with a backup suffix before overwriting it (sed offers such an option as well).

The same technique is often used for configuration files even if your program is writing an entirely new version and doesn't use the original file for that. It hasn't been long since many internet magazines claimed that ext4 accidentally truncates configuration files to zero length. This was exactly because some applications kept the configuration files open and truncated while the system was forcedly shut down. Those application often tampered with the original configuration files before they had the data ready and then even kept them open without syncing them, which made the window for data corruption much larger.

TL;DR version:

When you value your data, don't destroy it before you have the replacement data ready.

2 of 5
9

No, there's no way to insert characters into an existing file. You will need to use a second file to do that.

Top answer
1 of 4
13

Here's a function extend_file_and_insert() that does the job, more or less.

#include <sys/stat.h>
#include <unistd.h>

enum { BUFFERSIZE = 64 * 1024 };

#define MIN(x, y) (((x) < (y)) ? (x) : (y))

/*
off_t   is signed
ssize_t is signed
size_t  is unsigned

off_t   for lseek() offset and return
size_t  for read()/write() length
ssize_t for read()/write() return
off_t   for st_size
*/

static int extend_file_and_insert(int fd, off_t offset, char const *insert, size_t inslen)
{
    char buffer[BUFFERSIZE];
    struct stat sb;
    int rc = -1;

    if (fstat(fd, &sb) == 0)
    {
        if (sb.st_size > offset)
        {
            /* Move data after offset up by inslen bytes */
            size_t bytes_to_move = sb.st_size - offset;
            off_t read_end_offset = sb.st_size; 
            while (bytes_to_move != 0)
            {
                ssize_t bytes_this_time = MIN(BUFFERSIZE, bytes_to_move);
                ssize_t rd_off = read_end_offset - bytes_this_time;
                ssize_t wr_off = rd_off + inslen;
                lseek(fd, rd_off, SEEK_SET);
                if (read(fd, buffer, bytes_this_time) != bytes_this_time)
                    return -1;
                lseek(fd, wr_off, SEEK_SET);
                if (write(fd, buffer, bytes_this_time) != bytes_this_time)
                    return -1;
                bytes_to_move -= bytes_this_time;
                read_end_offset -= bytes_this_time; /* Added 2013-07-19 */
            }   
        }   
        lseek(fd, offset, SEEK_SET);
        write(fd, insert, inslen);
        rc = 0;
    }   
    return rc;
}

(Note the additional line added 2013-07-19; it was a bug that only shows when the buffer size is smaller than the amount of data to be copied up the file. Thanks to malat for pointing out the error. Code now tested with BUFFERSIZE = 4.)

This is some small-scale test code:

#include <fcntl.h>
#include <string.h>

static const char base_data[] = "12345";
typedef struct Data
{
    off_t       posn;
    const char *data;
} Data;
static const Data insert[] =
{
    {  2, "456"                       },
    {  4, "XxxxxxX"                   },
    { 12, "ZzzzzzzzzzzzzzzzzzzzzzzzX" },
    { 22, "YyyyyyyyyyyyyyyY"          },
};  
enum { NUM_INSERT = sizeof(insert) / sizeof(insert[0]) };

int main(void)
{
    int fd = open("test.dat", O_RDWR | O_TRUNC | O_CREAT, 0644);
    if (fd > 0)
    {
        ssize_t base_len = sizeof(base_data) - 1;
        if (write(fd, base_data, base_len) == base_len)
        {
            for (int i = 0; i < NUM_INSERT; i++)
            {
                off_t length = strlen(insert[i].data);
                if (extend_file_and_insert(fd, insert[i].posn, insert[i].data, length) != 0)
                    break;
                lseek(fd, 0, SEEK_SET);
                char buffer[BUFFERSIZE];
                ssize_t nbytes;
                while ((nbytes = read(fd, buffer, sizeof(buffer))) > 0)
                    write(1, buffer, nbytes);
                write(1, "\n", 1);
            }
        }
        close(fd);
    }
    return(0);
}

It produces the output:

12456345
1245XxxxxxX6345
1245XxxxxxX6ZzzzzzzzzzzzzzzzzzzzzzzzZ345
1245XxxxxxX6ZzzzzzzzzzYyyyyyyyyyyyyyyYzzzzzzzzzzzzzzZ345

It should be tested on some larger files (ones bigger than BUFFERSIZE, but it would be sensible to test with a BUFFERSIZE a lot smaller than 64 KiB; I used 32 bytes and it seemed to be OK). I've only eyeballed the results but the patterns are designed to make it easy to see that they are correct. The code does not check any of the lseek() calls; that's a minor risk.

2 of 4
5

First, use ftruncate() to enlarge the file to the final size. Then copy everything from the old end over to the new end, working your way back to the insertion point. Then overwrite the middle contents with the data you want to insert. This is as efficient as it gets, I think, because filesystems don't generally offer true "insertion" in the middle of files.

๐ŸŒ
The Open Group
pubs.opengroup.org โ€บ onlinepubs โ€บ 009695099 โ€บ functions โ€บ write.html
write
When attempting to write to a file descriptor (other than a pipe or FIFO) that supports non-blocking writes and cannot accept the data immediately: If the O_NONBLOCK flag is clear, write() shall block the calling thread until the data can be accepted. If the O_NONBLOCK flag is set, write() shall not block the thread. If some data can be written without blocking the thread, write() shall write what it can and return the number of bytes written.
๐ŸŒ
GeeksforGeeks
geeksforgeeks.org โ€บ c language โ€บ basics-file-handling-c
File Handling in C - GeeksforGeeks
2 weeks ago - The file write operations can be performed by the functions fprintf() and fputs(). C programming also provides some other functions that can be used to write data to a file such as:
๐ŸŒ
Reddit
reddit.com โ€บ r/cpp_questions โ€บ how to output to a text file, without overwriting what was already on it?
r/cpp_questions on Reddit: How to output to a text file, without overwriting what was already on it?
July 16, 2020 -
#include <iostream>
#include <fstream>

using namespace std;

int main()
{
	ofstream myText;
	int i = 0, arr[3] = { 1, 2, 3 };
	myText.open("text.txt");
	while (i < 3)
	{
		myText << arr[i];
		i++;
	}
	myText.close();

	return 0;
}

(Simplified code)

When I run the program, it outputs '123', but when I run it again, instead of there being '123123', it is just '123'. How do I fix this?

๐ŸŒ
Reddit
reddit.com โ€บ r/c_programming โ€บ writing to a file atomically using c
r/C_Programming on Reddit: Writing to a file atomically using C
July 31, 2023 - My best guess is to just fwrite ... to this problem I've found online is to write to a secondary file and then renaming it to the original file, making the operation atomic....
๐ŸŒ
Reddit
reddit.com โ€บ r/c_programming โ€บ write() is not writing the entire string to the file
r/C_Programming on Reddit: write() Is Not Writing The Entire String to the File
October 18, 2020 -

I'm currently tinkering around with a project and I'm having bit of an issue with my write command.

Right now I have the following:

for (int i = 1; i < count; i++) {

	char* fileByYear[5];
	sprintf(fileByYear, "%d.txt", movieArray[i].year);

	char* buffer[50];

	printf("\nCalling sprintf on string creation -- ");
	sprintf(buffer, "%s\n", movieArray[i].title);
	printf("%s\n", buffer);

	int fd = open(fileByYear, O_RDWR | O_CREAT | O_APPEND | O_TRUNC, 0640); 
	write(fd, buffer, strlen(buffer +1));
        close(fd);
}

My printf on the buffer confirms the string is being corrected correctly with sprintf()

Calling sprintf on string creation -- The Incredible Hulk
Calling sprintf on string creation -- Sherlock Holmes
Calling sprintf on string creation -- Iron Man

But with what is being written the file files is:

2008.txt >> I

2009.txt >> sherlock

It seems the whole string isn't being written correctly. I believe it maybe an issue with my permissions. The permissions are set to:

The permissions on these files must be set to

rw-r-----
  • i.e., the owner can read and write to the file, while group can only read the file.

The possible issue is the files aren't being saved into the directory that is being created, but I'm still trying to figure that out

๐ŸŒ
University of Utah
users.cs.utah.edu โ€บ ~germain โ€บ PPS โ€บ Topics โ€บ C_Language โ€บ file_IO.html
C Programming - File Input/Output
In the case of reading data, usually, ... basic syntax for opening a file and writing to or reading from it: FILE *in_file = fopen("name_of_file", "r"); // read only FILE *out_file = fopen("name_of_file", "w"); // write only // test for files not existing....
๐ŸŒ
Guru99
guru99.com โ€บ home โ€บ c programming โ€บ c files i/o: create, open, read, write and close a file
C Files I/O: Create, Open, Read, Write and Close a File
August 8, 2024 - We can write to a file after creating its name, by using the function fprintf() and it must have the newline character at the end of the string text. ... Stay Updated on AI Get Weekly AI Skills, Trends, Actionable Advice.
๐ŸŒ
GeeksforGeeks
geeksforgeeks.org โ€บ c language โ€บ fopen-for-an-existing-file-in-write-mode
fopen() for an existing file in write mode - GeeksforGeeks
July 23, 2025 - Following is modified C11 program that doesn't overwrite an existing file. ... #include <iostream> #include <cstdlib> int main() { FILE *fp = fopen("test.txt", "wx"); if (fp == NULL) { puts("Couldn't open file or file already exists"); exit(0); } else { fputs("GeeksforGeeks", fp); puts("Done"); fclose(fp); } return 0; } // This code is contributed by sarajadhav12052009