May I impose on you guys again? I'm trying to learn how to write
to disk into a file. I think I got that down, however I would like to
be able to display to screen the same text is being written to file.
What's a way of doing that?. Do I have to repeat the string using "printf"?.

Here's the sample code:

/*
 *    open_file.c
 *    trying to create a file.
 *
 */
 
 #include <stdio.h>


#define    FILE_NAME    "C:\\progdir\\openf\\text.txt"

void    end_it()
{
    printf("\nProgram ended. Press enter to exit: ");
    fflush(stdin);    /* workes with this compiler */
    getchar();
}

int main(void)
{
    FILE    *file_ptr;    /* structure pointer */
    
    atexit(end_it);        /* call end_it at anytime it exit */
    
    
    file_ptr = fopen(FILE_NAME, "w");
    if(file_ptr == NULL)
    {
        fprintf(stderr, "Could not open %s\n",
                        FILE_NAME);  
          exit(1);
    }
    
    /*
     *    Test to see if we can write to the file
     */
    if    (fprintf(file_ptr, "Initial success in writing to file\n\n") < 0)
    {
        perror("Could not write to the file");
        fclose(file_ptr);
        exit(1);
    }
    fprintf(file_ptr, "More writing text here.\nAnd here I keep writing some more\n");
    
    /*
     *    Close file
     */    
    fclose(file_ptr);
    
    return(0);
}

Do I have to repeat the string using "printf"?.

Nope, if you think about it really hard it prints itself out automatically. The computer's smart enough to figure out your thoughts.

No, but seriously what did you expect? Just repeat the printf() statement, although to make it easier you may want to store the literals in const char strings to make the code look cleaner.

No, but seriously what did you expect?

I was not sure that I could use the same fprintf() to re-directed to the file and to the screen using stdout as a parameter.

although to make it easier you may want to store the literals in const char strings to make the code look cleaner.

when you say const char strings are you refering to an array of chars?

when you say const char strings are you refering to an array of chars?

Yes something of that sort, only thing to be taken care is that, the string literal should be constant.

const char name[] = "Daniweb" ;

Thank you again.
You both have been very helpful.

Another thing you need to consider is fflush(stdin); /* workes with this compiler */ doesn't work with most. Don't get into a habit that will be hard to break later. It may work now, but it is wrong

commented: Good show! - Salem +6

Another thing you need to consider is fflush(stdin); /* workes with this compiler */ doesn't work with most. Don't get into a habit that will be hard to break later. It may work now, but it is wrong

Mr WaltP,
Even when I wrote that weak comment, I had the feeling that sooner than later you would tell me something about that fflush(stdin). :)
And I agree!. The problem is I still don't know how to read and check
the stdin correctly. I have been trying to understand it, but I'm not happy with the solution.
This is a piece of code that proves my ignorance:

/*
 * fgets.c
 * Understand the beheviour of fgets and
 * the \n and \0 character.
 *
 */
 #include <stdio.h>
#include <string.h>

 void fflush_stdin(FILE *extra);  /* prototype */

int main(void)
{
    char  answer[20]; /* array that can hold 21 characters */
    int length = 0;   /* for length of string */
    
  /* display first invitation */
    printf("Enter a string: ");   
    fflush(stdout);            /* flush the output file */
    
  /* read the first answer */
    fgets(answer, sizeof answer, stdin);
    length = strlen(answer);   /* get how many array elements are in the string */
    if(answer[length -1] == '\n') /* is the char before last a "new line"? */
    {
        answer[length -1] = '\0'; /* if the char before last is a '\n' overwrite with a '\0' */
    }
    fflush_stdin(stdin); /* first call to flush the stdin file */
    
    
  /* display first answer and length */
    printf("first read >>>%s<<< with >>>%d<<< length\n", answer, length);
    
  /* display second invitation */
    printf("Enter a second string: ");
    fflush(stdout);
    
  /* read second answer */
    fgets(answer, sizeof answer, stdin);
     length = strlen(answer);   /* get how many array elements are in the string */
    if(answer[length -1] == '\n') /* is the char before last a "new line"? */
    {
        answer[length -1] = '\0'; /* if the char before last is a '\n' overwrite with a '\0' */
    }
    
  /* call to flush the stdin file */
    fflush_stdin(stdin);
    
  /* display second answer */
   printf("second read >>>%s<<< with >>>%d<<< length\n", answer, length);
   
   fflush_stdin(stdin);
   getchar();
   
   return(0);
}

void fflush_stdin(FILE *extra)
{
    char ch;
    
    do
    {
        ch = getchar();
    }
    while( ch != EOF && ch != '\n');
}

If the string entered is larger than the capacity of the array the fflush_stdin function cleans it, but if the answer is less,...well it pauses and waits and I have to press twice to continue.


What would be you sugestion?.

I suggest you read this:
http://www.daniweb.com/tutorials/tutorial45806.html

[edit]
Well actually, writing your own flushing function like you showed in your snippet is actually alright. When you use getchar() to remove stray charecters until the newline, that's actually correct. But perhaps it would be a better idea to use a different function name so as not to confuse other people helping you with your code? :P

Mr WaltP,
Even when I wrote that weak comment, I had the feeling that sooner than later you would tell me something about that fflush(stdin). :)
And I agree!. The problem is I still don't know how to read and check
the stdin correctly. I have been trying to understand it, but I'm not happy with the solution.

Well, you could click on the link I gave you... That might be a first step ;)

By the way, how did you get the color in the code you posted?

By the way, how did you get the color in the code you posted?

By manually coloring it...

If the string entered is larger than the capacity of the array the fflush_stdin function cleans it, but if the answer is less,...well it pauses and waits and I have to press twice to continue.

What would be you sugestion?.

Flushing should be conditional. If you know there are no more characters in the stream, don't flush it. :) You can be sure that there aren't any unwanted characters after a '\n' for stdin because of how C buffers input.

if ( fgets( answer, sizeof answer, stdin ) ) {
  char *p = strchr( answer, '\n' );

  if ( p )
    *p = '\n';
  else
    flush_stdin();
}

That's not guaranteed if somebody redirects the stream to a file, but for interactive input it works like a charm. :)

By the way, how did you get the color in the code you posted?

By manually coloring it...

I was asking the poster because I can't believe everyone that has color tags is actually doing it himself... :confused:

@WaltP

I was asking the poster because I can't believe everyone that has color tags is actually doing it himself...

I colored it using the A in the post editor. I think is easier to read, at least for me.

I appreciated the link that you posted. I noticed that the author signature is WaltP also. Is that you?.

I think finally understood, by reading that tutorial, that if I collect the
answer using the right code I would not have to clean the stdin using
fflush(stdin). My error is that I was trying to create a function that
would act like flushing the buffer, and it was not beutiful at all.

I colored it using the A in the post editor. I think is easier to read, at least for me.

*groan* Don't you know there's an easier way? Simply encase your code in [code=c] and [/code] for C code or [code=cplusplus] and [/code] for C++ code..

It's MUCH easier, and then it at least makes some sort of standard code-coloring method here.

I appreciated the link that you posted. I noticed that the author signature is WaltP also. Is that you?.

Who else would post something so good :cheesy:

Mr WaltP,
Well done, in the explanation you give of avoiding gets()

However, I put together the piece of code that you sugested, and I must be missing something or I did not understand the last portion of it, because is not working for me.

Here's from the link you re-directed me:

#include <stdio.h>

int main()
{
    char  b1[] = "ABCD";
    char  b2[] = "LMNO";
    char  b3[] = "ZYXW";
    char dummy[50];

    puts(b1);
    puts(b2);
    puts(b3);
    putchar('\n');

    puts("Enter some characters:");
    fgets(b2, 5, stdin);  /* 5 is the size of buffer b2 */
    if (b2[strlen(b2)-1] == '\n')
    {   /* full input line read */
        b2[strlen(b2)-1] = '\0';  /* remove the new-line */
    }
    else
    {   /* parial input line read */
        b2[0] = 0;  /* empty the b2 buffer */ 
        do
        {   
            fgets(dummy, 50, stdin);
            strcat(b2, dummy);  /* Save input but be sure */
                            /* sure to test your buffer size */
        } while (dummy[strlen(dummy)-1] != '\n');
    }

    putchar('\n');
    puts(b1);
    puts(b2);
    puts(b3);
    
     getchar();
    return(0);
}
/* 
I entered:  "thisisalongstring" 
Output:

ABCD
LMNO
ZYXW

Enter some characters:
thisisalongstring

ABCD
isalongstring

ZYXW
 */

What did I not get?. I know you're trying to clear the stdin buffer using a dummy array in the else statement, but why the array b2 needs to be set to 0, and then why you want to append to that whatever remains in the stdin?

I'm sorry if I'm being a pest.

if ( fgets( answer, sizeof answer, stdin ) ) {
  char *p = strchr( answer, '\n' );

  if ( p )
    *p = '\n';
  else
    flush_stdin();
}

Another lesson in pointers by Ravalon :)
I looked up the reference for strchr() to see what it does and my understanding is that it searchs for the character that you specify in this case '\n' and set the pointer to it. Correct?.
Why then you assign *p = '\n'; in the second if(). Shouldn't be *p = '\0'?

Mr WaltP,
Well done, in the explanation you give of avoiding gets()

Thank you.

However, I put together the piece of code that you sugested, and I must be missing something or I did not understand the last portion of it, because is not working for me.

if (b2[strlen(b2)-1] == '\n')
    {   /* full input line read */
        b2[strlen(b2)-1] = '\0';  /* remove the new-line */
    }
    else
    {   /* parial input line read */
        b2[0] = 0;  /* empty the b2 buffer */ 
        do
        {   
            fgets(dummy, 50, stdin);
            strcat(b2, dummy);  /* Save input but be sure */
                            /* sure to test your buffer size */
        } while (dummy[strlen(dummy)-1] != '\n');
    }

What did I not get?. I know you're trying to clear the stdin buffer using a dummy array in the else statement, but why the array b2 needs to be set to 0, and then why you want to append to that whatever remains in the stdin?

For what you are trying to do, you probably don't want to zero b2 and load dummy into b2 . How many characters did you read into dummy ? What size is b2 ? Can all those characters fit?

Think about what you want to do if you enter "thisisalongstring"? Since b2 is only size 5, do you want to output
this
isal
ongs
trin
g

? If so, you don't want the else at all. Just loop back and you'll read the next 4 characters. If not and you want all characters after "this" tossed, in the else you want to read the rest of the line until you've read the '\n' and leave b2 alone.

I'm sorry if I'm being a pest.

Nope, you're not being a pest. You are learning. If you don't ask, you don't learn. ;)

Another lesson in pointers by Ravalon :)
I looked up the reference for strchr() to see what it does and my understanding is that it searchs for the character that you specify in this case '\n' and set the pointer to it. Correct?.
Why then you assign *p = '\n'; in the second if(). Shouldn't be *p = '\0'?

Yes and yes. :cheesy: There's another lesson there too, that even the most experienced of programmers can and will mess up the little things all too often. ;)

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.