Embek
Embek

Reputation: 27

How to write using space and more than one line in C?

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

Answers (3)

user2517419
user2517419

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

R Sahu
R Sahu

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

saurabh agarwal
saurabh agarwal

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

Related Questions