remove newline characters from text file while writing data - c

I am getting a newline character into a text file while I was writing some content into the text file using the code below
sprintf(str,"GodownName,LorryNumber,InvoiceNumber,CementCompanyName,RcvdPrsnName,RcvdPrsNDsgnation,EntityQty,Date\0");
write(fd,str,strlen(str));
the text is writing from 2nd row and an unwanted newline is writing at 1st row. I want my text to be written from 1st row. So please any one help me to remove newline characters or spaces from text file
Thanks in advance

My guess is that you have another function which writes in fd before the call of this function.
Besides, writing "\0" at the end of a string litteral is useless, there's already one.

You do not need the \0 at the end. Is str long enough? If not that could cause the problem that you are encountering.

Related

Why does adding a \n character while appending make it possible to print out the last appended line?

I am trying to write some C code that appends a line of text to a file, and then simply display it line by line. When I open the file in append mode and add a line using fprintf, the line gets added and I can see it when I open the file with a text editor. However when I call a function to display all lines (which works fine before the new text is appended), I get all the lines until the last but excluding the new appended line.
Here is the code I'm working with. The first function just adds a new line, and the second function just reads all the lines. The read_csv() works initially when I haven't appended any lines through code and have just used a text editor to add my initial lines.
void add_record(const char* csv_filename)
{
FILE *f = fopen(csv_filename,"at");
char str="My appended line "
fprintf(f,"%s",str);
fclose(f);
}
void read_csv(const char* csv_filename)
{
FILE *f = fopen(csv_filename,"rt");
char str[MAX];
fgets(str,MAX,f);
while(!feof(f))
{ fputs(str,stdout);
fputs("\n",stdout);
fgets(str,MAX,f);
}
fclose(f);
}
Now I found two fixes to my problem but I don't exactly understand why they work.
Fix 1 : Adding an extra fgets() prints the missing appending line when I'm trying to display it, however when I use it to display my original text file it prints the last line twice..so not a good fix.
fgets(str,MAX,f)
while(!feof(f))
{ fputs(str,stdout);
fputs("\n",stdout);
fgets(str,MAX,f);
}
fgets(str,MAX,f)
Fix 2 : Adding a new line character at the along with the string appended fixes the problem perfectly and everything is smooth. All the lines get displayed when I call read_csv().
char str="My appended line "
fprintf(f,"%s\n",str)
Looking at the docs for fgets(), it says it reads until either a new line character or eof has reached(whichever occurs first), so I don't understand why my appended line get ignored by fgets().
When fgets() reaches the last line(which it skips) the situation I presume is something like this: it gets a string with " text text text eof",and it breaks out the loop skipping the print statement. But then when I use an extra fgets() outside the while loop it works. Also when I add a new line and the situation is a string like " text text text \n eof", it doesn't quit the loop and goes on to display it.
I would really appreciate if I could get some info on what is happening and why these two fixes work. I suspect it is something to do with the feof detecting an eof or some specifics about fgets but I couldn't find anything satisfactory online.
Thank you so much in advance for taking the time to read and respond.

Jump to end of specific line

I am trying to change my cursor position in an opened file.
fp = fopen("dirty", "a+");
fprintf(fp, "Text at end of file");
// seek to end of third line (eg.)
fprintf(fp, "Text at end of third line");
I have tried closing and reopening the file, and fseek, which didn't work.
Any help would be greatly appreciated.
To find a position in a file, use fseek(). There is no knowledge in C/C++ file handling to know about where lines start and/or end, other than in the sense that there are "end of line markers", newline ('\n').
To know where a line starts or ends you have to track that yourself (e.g. by reading the file character by character with fgetc(), element by element with fscanf() or line by line fgets() and when you find certain important parts, use ftell() to save the current position.
Note that whilst it may appear that fgets() knows about lines, it really just reads from where you are in the file, and when the character is a newline, it stops. But there's no knowledge available about "this line is 40 characters long".
You'll have to fseek to the beginning of the file, then read char by char with getc until you found the third newline, then ungetc (which can only unget exactly one character). Note however that you cannot insert text after the third line without overwriting the fourth.
(Inserting in the middle of a file is usually performed by copying the initial part, writing the new data, and then copying the final part.)

C - sorting a list on words in a text file

Wondering what method would be most suitable, and maybe, if someone would be so kind, how to start such a function for:
AWord
DWord
CWord
BWord
To end up in a new text file like:
AWord
BWord
CWord
DWord
At the moment, my program, reads each word line by line fgets() and does some stuff to it, capitalises the first letter etc. Once all that is done, a new text file is created, text.out.
I then want to sort it into alphabetical order, since all the words are only alphabetic, some maybe terminating with a number.
Thanks, any help is appreciated!
T.C
You said that you don't have an array of words, but that you read each line into a separate character array. This is what you need to fix. Declare char *lines[MAXLINES], an array of every line from your input file. Read each line from your input file in to that array. Then you can sort that array before putting it back out.
This is pretty much identical to the concepts presented in K&R Section 5.6 and 5.11.

\n characters before EOF in file causing problems

I have written some data to a file manually i.e. not by my application.
My code is reading the data char by char and storing them in different arrays but my program gets stuck when I insert the condition EOF.
After some investigation I found out that in my file before EOF there are three to four \n characters. I have not inserted them. I don't understand why they are in my file.
Want to remove those pesky extra characters? First, see how many of them there are at the end of your file:
od -c <filename> | tail
Then, remove however many characters you don't like. If it's 3:
truncate -s -3 <filename>
But overall, if it were me, I'd change my program to discard undesired newline characters, unless they're truly invalid according to the input file format specification.
It is very easy to add additional newlines to the end of a file in every text editor. You have to push the cursor around to see them. Open your file in your editor and see what happens when you navigate to the end, you'll see the extra newlines.
There is no such thing as an EOF character in general. Windows treats control-Z as EOF in some cases. Perhaps you are talking about the return value from some API that indicates that it has reached the end of file?

How to go to the previous line in a C code

If for the following code:
printf("HEllo\n"); // do not change this line.
printf("\b\bworld");
I need an output: Helloworld (In a single line). But this does not work fine. Could anyone please explain the reason? And other escape sequence if any.
There is no platform-independent control character to move back up a line. This harkens back to the days of line printers, where printf actually would print a line of text onto a sheet of paper and there was no way of retracting the paper to overwrite what had already been printed.
That said, there are libraries like ncurses that let you move the cursor around the console. They're just not part of the standard libraries.
How about simply:
printf("Helloworld");
\n is an escape sequence for a new line. Since you want everything to appear on the same line, there's no reason to specify \n.
The problem is you can't reliably move back up a line (using \b) after you've printed a new line. But if you require that there be two lines of code in your source, you can simply omit both escape sequences:
printf("HEllo");
printf("world");
If you're writing a Win32 console application, you can take advantage of the Console Screen Buffer API. The following code will move 1 line up:
printf("HEllo\n");
CONSOLE_SCREEN_BUFFER_INFO coninfo;
HANDLE hConsole = GetStdHandle(STD_OUTPUT_HANDLE);
GetConsoleScreenBufferInfo(hConsole, &coninfo);
coninfo.dwCursorPosition.Y -= 1; // move up one line
coninfo.dwCursorPosition.X += 5; // move to the right the length of the word
SetConsoleCursorPosition(hConsole, coninfo.dwCursorPosition);
printf("world");
Output:
HElloworld
Remove "\n" from your first printf. It moves the cursor to a new line.
Here is the list of escape sequences.
If you can't remove "\n", then you can do make a copy of a substring without these charaters. See the following example:
const char* from = "12345678";
char *to = (char*) malloc(6);
strncpy(to, from+2, 5);
All you need is to determine the index of "\n" characters.
The backspace character, when sent to a stream (such as through the printf() family of functions), does not seek backward in the file, it is sent as-is. If you run your example, the backspace character will be output as "garbage".
If you don't want a new line, don't post a newline character.
It is because '\b' is a terminal escape code... (sans the 'escape' of course ;-)
so it only modifies what you see on the terminal. That is, the terminal adjusts its display to respond to the backspace code, even though it received everything prior to it. A file also receives everything, including the backspace code, but it is not a tty device so the file's content is not modified; it keeps everything you send to it.
If printing an extra blank is a problem, then you should code some extra logic to print the trailing blank on every output except the last.
Reference This is in reference to files but maybe same idea applies. You might want to check out this link there is a very detailed explanation that most probably answers your question.
In a console, you can't go up a line. You can clear the screen and redraw it (which simulate going up a line.) Or you can rewrite on the same line. \r will take you to the beginning of the line you just printed.
You can do it actually in a platform-independent* way, assuming that you can somehow calculate the x offset of the previous line.
int x = printf("Hello, World!\n");
gotoxy(x-1-1,gety()-1); // One for the length-offset difference and the other to skip \n
printf("\b \b");
You can avoid using that variable by directly replacing it with x.
Note: printf() returns an int (the length of the passed String (of characters)). Use it wisely :)

Resources