Reputation: 27
I want to write a text and save it in .txt using <stdio.h>
and <stdlib.h>
. But with this way, I only could save one line, no more.
int main()
{
file*pf;
char kar;
if ((pf = fopen("try.txt","w")) == NULL)
{
printf("File couldn't created!\r\n");
exit(1);
}
while((kar=getchar()) != '\n')
fputc(kar, pf);
fclose(pf);
}
Upvotes: 0
Views: 202
Reputation:
Full Working Code which puts multiple line into your text file. To end the input from terminal just press Ctrl + Z
#include <stdio.h>
#include <stdlib.h>
int main()
{
FILE *pf;
char kar;
if ((pf = fopen("try.txt","w")) == NULL)
{
printf("File couldn't created!\r\n");
exit(1);
}
while((kar=getchar()) != EOF)
fputc(kar, pf);
fclose(pf);
return 0;
}
Upvotes: 0
Reputation: 206667
Instead of
char kar;
...
while((kar=getchar()) != '\n')
fputc(kar, pf);
use
int kar;
// Use int for type of kar
...
while((kar=getchar()) != EOF )
// ^^^
fputc(kar, pf);
Upvotes: 3
Reputation: 2184
'\n'
means end of line. Here, you are looking for end of file. So, use macro EOF
instead of '\n'
in your code.
Upvotes: 2