0
#include  <stdio.h>
#include  <stdlib.h>

#define MAX_LENGTH 100

FILE * openFile( char * mode )
{
    FILE *file;
    char name[50];

    printf("Enter a name of a file:\n");
    scanf("%49s", name);

    file = fopen(name, mode);

    if( ! file )
    {
        printf("Error opening the file.\n");
        exit( 1 );
    }

    return file;
}

int main ( int argc, char * argv [] )
{
    char row[MAX_LENGTH];

    printf("Output file:\n");
    FILE *output = openFile("w");

    while( fgets(row, MAX_LENGTH, stdin) ) /*Stops with EOF (ctrl+d - Unix, ctrl+z - Windows)*/
    {
        fputs(row, output);
    }

    fclose(output);

    return 0;
}

Hello the above code should take the string from stdin and write it to the file.

I know that when I press enter, fgets will read a new line. I'm OK with that.

Problem is that I also have a newline at top of the file I created and I dont know why.

I would appreciate any explenation. Thanks

guderkar
  • 133
  • 1
  • 10

2 Answers2

0

A work around you can make is to move the pointer to the beginning of the file.

void rewind(FILE *stream);

And it is equivalent to

fseek(stream, 0L, SEEK_SET);

You can check this post to: Does fseek() move the file pointer to the beginning of the file if it was opened in "a+b" mode?

Community
  • 1
  • 1
Ahmed Hamdy
  • 2,547
  • 1
  • 17
  • 23
0

Abhi thanks for the info. I made some research and this function does the job.

void flushStream( FILE * stream )
{
    while( 1 )
    {
        int x = fgetc(stream);
        if( x == '\n' || x == EOF ) break;
    }
}

.....

printf("Output file:\n");
FILE *output = openFile("w");

flushStream(stdin);

while( fgets(row, MAX_LENGTH, stdin) ) .........
guderkar
  • 133
  • 1
  • 10
  • By the way can anybody tell me if this function is legit? I know that using fflush(stdin) is not. So I dont know. – guderkar Feb 05 '14 at 11:29