If I am writing data to a .txt file, how can I get it to append to a newline instead of append to the first line?
Thanks in advance!
If I am writing data to a .txt file, how can I get it to append to a newline instead of append to the first line?
Thanks in advance!
Your question is a bit odd.
Well if you're using fprintf(), then by adding this line before you write the data:
fprintf(file, "\n");
you ensure that the data you write will be on a new line.
See that is what I thought too, but that doesn't work, it still just appends to the same line in the file.
Perhaps the editor you're using to view the file is fooling you.
Have you opened the file in append mode?
Otherwise post some code.
fp = fopen(DATAFILE, "a+");
fprintf(fp, "\n");
fprintf(fp, "Emp# ");
fprintf(fp, "%d", emp.eNum);
fprintf(fp, " ");
fprintf(fp, "| Name: ");
fprintf(fp, emp.fName);
fprintf(fp, " ");
fprintf(fp, emp.lName);
fprintf(fp, " ");
fprintf(fp, "| Hire Date: ");
fprintf(fp, emp.hDate);
fprintf(fp, " | ");
fprintf(fp, newstring); // DEPARTMENT: added with strcopy()
fprintf(fp, " ");
fprintf(fp, "| Salary: ");
fprintf(fp, "%2.2f", annualsalary);
//fprintf(fp, "\n");
fclose(fp);
Actually it could be because I am looking at the file in notepad, because when I open it in word, it opens on different lines
Alright, is there a way I can write to a text file, so it is actually on a newline when I open it in textpad? instead of just have the newline character appended to the first line? Because I need to read in the file line by line and display it on to the screen line by line....
Thoughts?
Well if you move the newline from the beginning to the end, then it should all work just nicely
Code:fp = fopen(DATAFILE, "a+"); // fprintf(fp, "\n"); // not here fprintf(fp, "Emp# "); fprintf(fp, "%d", emp.eNum); fprintf(fp, " "); fprintf(fp, "| Name: "); fprintf(fp, emp.fName); fprintf(fp, " "); fprintf(fp, emp.lName); fprintf(fp, " "); fprintf(fp, "| Hire Date: "); fprintf(fp, emp.hDate); fprintf(fp, " | "); fprintf(fp, newstring); // DEPARTMENT: added with strcopy() fprintf(fp, " "); fprintf(fp, "| Salary: "); fprintf(fp, "%2.2f", annualsalary); fprintf(fp, "\n"); // newline here fclose(fp);
If you dance barefoot on the broken glass of undefined behaviour, you've got to expect the occasional cut.
If at first you don't succeed, try writing your phone number on the exam paper.