How to Append Text to a Text File in C++

Append to the end of a file in C

Open with append:

pFile2 = fopen("myfile2.txt", "a");

then just write to pFile2, no need to fseek().

How to append text to a text file in C++?

You need to specify the append open mode like

#include <fstream>

int main() {
std::ofstream outfile;

outfile.open("test.txt", std::ios_base::app); // append instead of overwrite
outfile << "Data";
return 0;
}

How to append text to a .txt file iteratively in c

You need to fflush after each fprintf to the file.

If stream points to an output stream or an update stream in which the most recent operation was not input, fflush()shall cause any unwritten data for that stream to be written to the file, and the last data modification and last file status change timestamps of the underlying file shall be marked for update.

That is,

for(int i=0;i<500;i++)
{
a = a+1;
b = b+1;
c = c+1;
printf("a = %d\tb = %d\tc = %d\n"); // printing to console
fprintf(fp,"%d,%d,%d\n",a,b,c); // printing to file
fflush(fp); /* <== here */
}

PS: Whitespace is not a scarce commodity.

Append a text to a beginning of a file in C does not work

since you're using a temporary file, a secondary buffer should not be required, just append the text, then move the old file contents into the new one.

A few things you should lookout for,

  • if (!fp1 && !fp2) is only true if both files failed to be opened ,its better to check the results individually so we know where we failed. You could have replaced && with || but it will be ambiguous why it failed unless you re-check the file pointer values.
  • It seems you were never writing the data from fp1 into fp2 I only see calls to fgets(), you read fp1 into buf then you read fp2 into buf, doing nothing with the data both times. If the files are larger than 100 bytes you'll end up with the last 100 or less bytes of data being stored in buf.
  • It's not necessarily the worst thing, but it is good practice to only open files with the permissions you require. opening a file you only need to read from in 'a+' mode is kind of odd
  • before creating new files its a good idea to check that a file doesn't already exist by that name. You might be better off to create the file in the system's temporary directory or a dedicated tmp dir for your program. Using a unique string for it's name is also a good idea. perhaps something like "[my prog]-[original file name]-[.tmp]" instead of such a general name.

A short example of a method that should work, with error checking (not necessarily the best error checking but gives you an idea where errors can occur):

#include <sys/types.h>
#include <sys/stat.h>
#include <errno.h>
#include <string.h>

int Prepend(char *string, char *file_name)
{
FILE *fp1 = NULL, *fp2 = NULL;
struct stat fs;
if (stat("temp_file", &fs) == 0) {
printf("Error, there is already a file named \"temp_file\" in the current working directory\n");
return -1;
}
if ((fp1 = fopen(file_name, "r")) == NULL) {
printf("Error : %s\n", strerror(errno));
printf("Failed to Open file %s\n", file_name);
return -1;
}
if ((fp2 = fopen("temp_file", "w")) == NULL {
printf("Error : %s\n", strerror(errno));
printf("Unable to create Temporary file\n");
fclose(fp1);
return -1;
}
if (fputs("Prepended String\n", fp2) == EOF) {
printf("Failed to write string to file\n");
fclose(fp1);
fclose(fp2);
if (remove("temp_file") != 0)
printf("Error : %s, while removing temp_file\n", strerror(errno));
return -1;
}
int c;
while((c = fgetc(fp1)) != EOF) {
if(fputc(c, fp2) == EOF) {
printf("Error while transfering data from %s to %s\n", file_name, "temp_file");
fclose(fp1);
fclose(fp2);
if (remove("temp_file") != 0)
printf("Error : %s, while removing temp_file\n", strerror(errno));

return -1;
}
}
fclose(fp1);
if (remove(file_name) != 0) {
printf("Error : %s, while removing %s\n", strerror(errno), file_name);
fclose(fp2);
return -1;
}


fclose(fp2);
if (rename("temp_file", file_name) != 0) {
printf("Error : %s, while renaming temp_file\n", strerror(errno));
return -1;
}
return 0;
}

fclose() can also return EOF on error and errno is set to indicate the error. However, any further access (including another call to fclose()) to the stream results in undefined behavior. so you can print the error but there isn't much you can do about it.

Appending text to a file

read file data and count character till EOF (End of file). Check if count is not equal to zero. If it is so append else don't. You have not provided whole code otherwise I would have compiled and then send you code as well.

Append text (string values) to each line to a txt-file

I hope that helps you, and I assume that you want to read a source file and append the text to the destination file, Look at the result

using System;
using System.IO;
using System.Linq;

namespace Stack_Overflow {
class Program {
static void Main(string[] args) {
StreamReader sr = new StreamReader("source.txt"); // read the source text file
string appendedText = sr.ReadLine(); // get the first line
sr.Close(); // close the stream

string[] lines = File.ReadAllLines("dest.txt"); // read the all lines of the destination text file to know the maximum line length
int maximumLineLength = lines.OrderByDescending(a => a.Length).First().ToString().Split(',').Length; // get maximum line length using LINQ

foreach (var line in lines) {
appendTheText(line, (maximumLineLength - line.Split(',').Length) + appendedText.Length, appendedText); // the second parameter here is the number of iterations that must we loop through each line
}

Console.WriteLine("Task finished successfully!");
Console.ReadLine();
}

static void appendTheText(string line, int iterationCount, string appendedText) {
StreamWriter sw = new StreamWriter("dest1.txt", true);
sw.Write(line);
for (int i = 0; i < iterationCount; i++) {
sw.Write($",{appendedText}");
}
sw.WriteLine();
sw.Close();
}
}
}

NOTE that you must exclude the comma when you want to get the length of the line because we have a line that has odd commas and another has even commas So when we try to append our text to the line that has odd commas, we will find that line has an extra value So I split the text with Comma



Related Topics



Leave a reply



Submit