Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Prepend text to a file in C

Tags:

c

file

io

I want to add a standard header to a file (or group of files) using C. These files could be quite large, so it would be a bad idea to load them into memory, or copy them into temporary files (I think).

Is there a way to simply prepend the header directly to each file?

The header itself is quite small, not more than 1 KB

like image 758
Daniel Kats Avatar asked Nov 14 '12 18:11

Daniel Kats


People also ask

How to prepend a file in C?

Just create a new file, write the data you are inserting, then copy the contents of the original file to the new file (do it block by block instead of loading the entire file into memory). Finally, delete the original file and rename the new file to match the original file.

How to read and append file in C?

Opening the file with the mode a+ (append, allowing reading) sets the file position at the beginning of the file, so the first call to fgets reads the first line. But in append mode, all writes are performed at the end of the file.

When to use sed to prepend text?

The sed solution can be simplified if the intent is to prepend one or more whole lines to the existing content (assuming the input file is non-empty): # Prepends 'to be prepended' *followed by a newline*, i.e. inserts a new line.

How do I prepend multiple lines in a text file?

# Prepends 'to be prepended' *followed by a newline*, i.e. inserts a new line. # To prepend multiple lines, use ' ' as part of the text. # -i.old creates a backup of the input file with extension '.old' sed -i.old '1 i o be prepended' inFile

How to open and read a text file in C?

The algorithm for opening and reading a text file in C has given below: Assign file pointer to fopen () function with write format The above source code is simple to understand and friendly due to the use of multiple comment lines.

What is the output of append command in C programming?

Output Output of this program should be − Contents of file_append.txt - This text was already there in the file. Appending content to file_append.txt... Content of file_append.txt after 'append' operation is - This text was already there in the file. This text is appeneded later to the file, using C programming.


1 Answers

You cannot insert data into a file.

However, there is no need to load the entire file in memory. Just create a new file, write the data you are inserting, then copy the contents of the original file to the new file (do it block by block instead of loading the entire file into memory).

Finally, delete the original file and rename the new file to match the original file.

This is the most efficient way to do this and it is reasonably efficient.

like image 168
Jonathan Wood Avatar answered Nov 15 '22 06:11

Jonathan Wood