How to add text at the end of line - c

for example I have test.txt with
test1
test2
at the end of each line I would like to add some text
my code is:
fp = fopen("test.txt", "w");
while ((ch=getc(fp)) != EOF)
if (ch == '\n')
fprintf(fp, "newText");
my output is:
test1
newText
The outcome should be:
test1newText
test2newText

You cannot do it with a single file.
Here is what you need to do:
Open an auxiliary file for temporary output
Read the actual file line by line
For each line write the copy of the line into the auxiliary output
After writing the line write the suffix that you would like to append
Go to the next line until you process the whole file
Once you finished processing the whole file, close both files, and move the auxiliary file in place of the original input.
How to avoid a new line?, I successfully copy [the text] but when I try to add some text at the end of each line, it starts from new line
This is because you include the end-of-line character in your copied text.
If you read character-by-character, do not copy '\n's when you see them; if you read with fgets, check the last character, and skip it if it happens to be '\n' (fgets includes it in its return value).

You can’t read from your output file like that. It is possible to open a file for reading and writing, but it’s an advanced topic and isn’t really appropriate for text files.
The normal approach is to write to another file, and then replace the original if desired. Note that you’ll have to emit all the characters you read and your extra text.
If this is the whole function of the program, consider making it a filter (by using the standard streams); this is what’s expected by experienced users and saves some error checking.

eventually, I have succeed
if (!strcmp(fileName, SWM_DEBUG))
{
fp = fopen(fileName, "r");
fpOut = fopen("tmp.txt", "w");
while ((ch = fgetc(fp)) != EOF)
{
if (ch == '\n')
fprintf(fpOut, "TEST");
fputc(ch, fpOut);
}
}
Thanks for your support ☺

You need to change the fopen call to read from the file and use the fputc function to re-output the character you read, like this:
fp = fopen("test.txt", "r");
while ((ch=fgetc(stdin)) != EOF) {
if (ch == '\n') {
fprintf(fp, "newText");
}
fputc(ch, fp);
}
fprintf(fp, "newText");
As pointed out elsewhere, you can't simultaneously read and write a file in the way you were trying to do, so i've changed it to read from stdin to illustrate the code

Related

C program to get first word of each line from a .txt file and print that word onto another .txt file: Kind of works but also prints random letters

So we have this file called dictionary1.txt and it has words with their pronounciation right next to them. What I want to do is to get the first word from each line and print them onto another txt file that the program creates from scratch. My code does it but it also prints random Chinese letters in between English words, I don't know why.
Here's what the ouput file looks like: https://imgur.com/a/pZthP
(Pronounciations are seperated from the actual words in each line with a blankspace in dictionary1.txt)
My code:
#include <stdio.h>
#include <stdlib.h>
int main(int argc, char *argv[]) {
char line[100];
int i = 0;
FILE* fp1 = fopen("dictionary1.txt", "r");
FILE* fp2 = fopen("dictionary2.txt", "w");
if (fp1 == NULL || fp2 == NULL){
printf("ERROR");
return -1;
}
while (fgets(line, 100, fp1) != NULL){
while (line[i] != ' '){
fputc(line[i], fp2);
i++;
}
i=0;
fputc('\0', fp2);
}
return 0;
}
I tried fputc('\n', fp2) as well bu t no matter what I couldn't get onto the next line in the file I created from scratch. I also can't get rid of all the random Chinese letters.
EDIT: I figured it out. The .txt file I was working on was saved in Unicode formatting, which didn't work well with my program. I turned it into ANSI and now it works like a charm.
\n is not the right line separator on all operating systems and all editors.
If you are editing your txt files on Notepad, try fputs ("\r\n", fp2);, where \r means carriage return (cursor returns at the first character of the line) and \n new line.
Generally speaking, Windows uses '\r\n' as line separator, the '\n' character is displayed as something else than end line, at least in Notepad. Linux and Mac OS use different line separators. You may also want to try fprintf(fp2, "\n");
Check this out
\n and \r seem to work everywhere. Why is line.separator more portable?
If you don't mind using C++, you could try to create an output stream os and write os << endl
Note that some compilers may automatically convert '\n' into the corresponding operating system end line character/caracther sequence, whereas some may not.
Another thing, change the while loop condition into line[i] != ' ' && line[i] != '\0' and close the file fp2 using fclose.
.txt file was saved using Unicode formatting. I turned it into ANSI and everything was suddenly fixed.

Remove empty new line at the end of a file

I have a file that's storing strings from the user's input (stdin)
However there are 2 situations
If I read it normally, my file will have an empty line at its end due to the newline from the last string the user introduced.
If I remove the \n from the input string, the file stores all strings in the same line, which is not wanted.
How can I simply remove that newline from the end of the file?
I can edit and provide some of my code if required.
EDIT: Let's say the last line of a file I already have is "cards"
when the cursor is in front of "cards", if I press the down arrow it doesn't go on to the next line, while in this case it can happen once.
For my code to function perfectly I can't let that happen,
Here's an example of what I have:
f=fopen(somefile, "w");
do
{
fgets(hobby, 50, stdin);
fprintf(f, "%s", hobby)
} while(strcmp(hobby,"\n") != 0);
The newline character1 at the end of the file is part of the last line. Removing it is possible but makes the last line incomplete, which will break many programs. For example, concatenating another file at the end of this file will cause the last line to be merged with the first line of the concatenated file.
A Yuri Laguardia commented, if you later reopen this file in append mode to write more lines, the first one added would be concatenated at the end of this last incomplete line. Probably not the intended behavior.
If you do not want the file to contain empty lines, check user input before writing the line into the file:
void input_file_contents(FILE *fp) {
char userinput[80];
printf("enter file contents:\n");
while (fgets(userinput, sizeof userinput, stdin)) {
if (*userinput != '\n') {
fputs(userinput, fp);
}
}
}
EDIT:
Your code does not test for termination at the right place: you write the empty line before the test. Do not use a do / while loop:
f = fopen(somefile, "w");
if (f != NULL) {
/* read lines until end of file or empty line */
while (fgets(hobby, 50, stdin) != NULL && *hobby != '\n') {
fputs(hobby, f);
}
}
1 The newline character is actually a pair of bytes <CR><LF> on legacy systems.

append text at the end of a line in a file pure c code

I need to append a text at the end of each line in a file. I have the following code:
FILE *tmp_copy = tmpfile();
file = fopen ( argv[2], "rw" );
if ((file != NULL )) {
char line [ 128 ]; /* or other suitable maximum line size */
while( ( fgets ( line, sizeof line, file ) != NULL )) {
fputs(line, tmp_copy);
}
fclose ( file );
rewind(tmp);
char *p;
/* Reopen file now with write permissions */
fopen(argv[2], "w");
while (( p = fgets(line, 1024, tmp))!=NULL) {
//line[strlen(line)-1] = '\0'; /* Clear away newline */
//sprintf(line, "%s %s\n", line, more);
strcpy(line,"true");
//fputs(line, file);
}
fclose(file);
fclose(tmp);
}
}
I ve edited my code. still not working
but it's not working. why?
I'm guessing you want the line to be re-written to the file again. However, you are not writing to the file, just appending to the data in memory. It's also really not possible to read and write files at the same time like that, you have to do it in two steps:
Read from original file, appending wanted text to line, and write to temporary file
Rename (or copy) from temporary file to the original file
Edit: Pseudo-ish code for my answer:
original_file = fopen(original_file_name, "r");
temporary_file_name = tmpnam("dummy");
temporary_file = fopen(temporary_file_name, "w");
while (fgets(line, original_file))
{
remove_trailing_newline(line);
strcat(line, " TRUE\n");
fputs(line, temporary_file);
}
fclose(temporary_file);
fclose(original_file);
rename(temporary_file_name, original_file_name);
Unless the file is memory-mapped AND fgets returns a pointer to the original buffer (it doesn't. It needs to append the null.) AND strcat operates in place (it does), then you are not storing anything, only messing up some memory. Even if it did work, you would overwrite a part of the next line anyways.
You need to either
Write to a temporary file and rename that after you close the original one (as suggested by Joachim Pileborg).
Write into a buffer in memory and save it to the file when you are done reading.
Read the file into memory in one go, then start reading the buffer line by line.

Reading the number of lines in a file

I need to calculate the number of lines in a file , however , I must do that without
the "easy" functions such as : fopen , fscanf ,fgets ... and so on .
Meaning I can't do this :
int calculateLines(char *filename)
{
FILE *myFile;
char c;
int myLines = 0;
myFile = fopen(filename, "r");
if(myFile == NULL)
return 0;
while ((c = fgetc(f)) != EOF)
if(c == '\n')
myLines++;
fclose(f);
if(c != '\n')
myLines++;
return myLines;
}
For that , I can use only the system calls read , write , close , open & fork.
From what I've done so far , I think that :
open the file with open : someResult = wrapper_open(argv[1],O_RDONLY,0);
reading line after line with read : Can I manipulate read somehow to read line after line ? I've tried to check with its tutorial however came empty handed .
You can't really read line-by-line with read. Instead, you'd read in a block of data (which might contain an arbitrary number of lines, and probably some partial lines). Count the new-line characters in that block, then repeat the read/count process 'til you reach the end of the file.

Reading a text file up to a certain character

Here's my dilemma. I have a file, and wish to read in all characters up until the program hits a '#', and ignore everything on that line after the '#'. For example
0 4001232 0 #comment, discard
This is frustrating, as it feels like there is a very simple solution. Thanks!
FILE *f = fopen("file.txt", "r");
int c;
while ((c = getc(f)) != '#' && c != EOF)
putchar(c);
Read a line using fgets, read through this line till you get a '#' character.
Read an another line...
There are plenty of ways and examples of how to do it. Usually, the idea is to have a variable that holds the state (before #, after # , after \n etc.) and run in a while loop until EOF. an example you can see here it's a program to remove C comments, but the idea is the same.
filePointer = fopen("person.txt", "r");
do
{
read = fgetc(filePointer);
//stop when '#' read or when file ends
if (feof(filePointer) || read == '#')
{
break;
}
printf("%c", read);
} while (1);
fclose(filePointer);
also you better check if file opened succesfully
if (filePointer == NULL)
{
printf("person.txt file failed to open.");
}
else
{
file operations
}
The solution depends on how you are "reading" that.
I could, for example, just remove all of those comments with sed 's/#.*//' <infile >outfile in bash.
EDIT: However, if I was parsing it manually, I could simply (in my loop for parsing it) have
if(line[i]=='#') {
continue;
}
which would stop parsing that line by exiting the loop.

Resources