Reputation: 11
#include <stdio.h>
int main ()
{
FILE * fp;
int i,n;
char str[20];
printf("Enter the number of lines to be written: ");
scanf("%d", &n);
fp = fopen ("abc.txt","w");
for(i = 0; i < n+1;i++)
{
gets(str);
fputs(str, fp);
}
fclose (fp);
return 0;
}
In this code, I am able to write multiple lines but when I check the result in the notepad, these multiple lines are displayed in a single line. How can I make them appear as I typed in the command prompt (here I am using Visual Studio 2008 command prompt).
Upvotes: 1
Views: 6826
Reputation: 1
As WhozCraig pointed out, gets is evil and is akin to asking for a buffer overflow.
But to answer your question, add a CRLF (carriage return + line feed) like such:
#include <stdio.h>
int main(void){
FILE* fp;
int n;
char str[20];
printf("Enter the number of lines to be written: ");
scanf("%d", &n);
fp = fopen ("abc.txt","w");
for(int i = 0; i < n+1;i++){
gets(str);
fputs(str, fp);
fputs("\r\n", fp);
}
fclose (fp);
return 0;
}
Upvotes: 0
Reputation: 1777
You replace existing so add
#include <stdio.h>
int main ()
{
FILE * fp;
int i,n;
char str[20];
printf("Enter the number of lines to be written: ");
scanf("%d", &n);
fp = fopen ("abc.txt","w");
for(i = 0; i < n+1;i++)
{
gets(str);
fputs(str, fp);
fputs("\n", fp);
}
fclose (fp);
return 0;
}
after add your input.
fputs("\n", fp);
add new line to your file abc.txt after your text get added.
Upvotes: 2
Reputation: 172458
You may try like this:
fputs("\n", fp);
ie, put a \n
to move to the next line. \n
is used as a newline character in C
Upvotes: 1
Reputation: 234715
You need to append \r\n to each line. (Carriage return plus line feed.)
UNIX requires just \n but some of the Windows tools don't deal with that well.
Upvotes: 0
Reputation: 201447
Add something like this,
fputs(str, fp);
fputs("\r\n", fp); /* add a Windows new line */
Upvotes: 1