fgets() 
Author Message
 fgets()

When I excecute this code using the fgets statements on lines 14-18
(approx). The code doesn't function properly, but when I use gets() it's
fine, but I get advised against using this method. The fgets() later on
causes no problems, anyone help?

#include <stdio.h>
#include <stdlib.h>
#define maxlen 120
int file_copy(char oldname[maxlen],char newname[maxlen]);

int main()
{

     char ch,source[maxlen],destination[maxlen],input[maxlen];

     printf("Enter a source filename: ");
     fgets(source,maxlen,stdin);
     printf("Enter destination filename: ");
     gets(destination,maxlen,stdin);

      if (file_copy(source,destination)==0)

          printf("Successful copying.");
       else
          fprintf(stderr,"\nError copying file.");
          printf("%d",file_copy(source,destination));

         /* ***************************** */
         /* this allows system operations */
         /* ***************************** */

         printf("\nInput desired system command, blank to exit\n");
         fgets(input,maxlen,stdin);
         system(input);

      return;
 }//end main

      /* write data to new  file */
int file_copy(char oldname[maxlen],char newname[maxlen])
{
     FILE *fpold,*fpnew;
     int c;
        /*open source file*/
      if ((fpold = fopen(oldname,"rb"))==NULL)
             return -1;

         /*open destination file*/
      if ((fpnew = fopen(newname,"wb"))==NULL)

             return -1;

          /*copy file*/
         while (!feof(fpold))
               {
                    c=fgetc(fpold);
                    fputc(c,fpnew);

             }

         fclose(fpold);
         fclose(fpnew);

        return 0;

Quote:
}//end function



Sun, 25 Aug 2002 03:00:00 GMT  
 fgets()


Quote:
> When I excecute this code using the fgets statements on lines 14-18
> (approx). The code doesn't function properly, but when I use gets()
it's
> fine, but I get advised against using this method. The fgets() later
on
> causes no problems, anyone help?

The problem is that you need to remove the '\n' that fgets
includes and gets does not.  fgets tries to read the entire
line and includes the newline character in the buffer if
it succeeds; otherwise it reads as much as it can (no '\n')
and leaves the rest in the stream.  You should also check the
return of fgets; if it's NULL, there was an error or end-of-file.

Quote:
> int main()
> {

>      char ch,source[maxlen],destination[maxlen],input[maxlen];

char *p;  /* for code added below */

Quote:
>      printf("Enter a source filename: ");
>      fgets(source,maxlen,stdin);
>      printf("Enter destination filename: ");
>      gets(destination,maxlen,stdin);

That should be fgets.

Add the lines
    if((p = strchr(source, '\n')) != NULL)
        *p = '\0';
    if((p = strchr(destination, '\n')) != NULL)
        *p = '\0';
as the FAQ suggests in the answer to question 7.1; this doesn't
check for an overly long line but gives a perfect replacement of
gets with fgets (since anyone who was using gets already didn't
care what the code did with overly long lines).  A more careful
program will check the return of fgets and the presence of '\n',
especially when you're going to write a file based on the string
returned.

--
MJSR

Sent via Deja.com http://www.deja.com/
Before you buy.



Sun, 25 Aug 2002 03:00:00 GMT  
 fgets()

Quote:

> When I excecute this code using the fgets statements on lines 14-18
> (approx). The code doesn't function properly, but when I use gets() it's
> fine, but I get advised against using this method. The fgets() later on
> causes no problems, anyone help?

Try the following
  ** changes **

2a3

Quote:
> #include <string.h>

9c11
<   char ch, source[maxlen], destination[maxlen], input[maxlen];
---
Quote:
>     char source[maxlen], destination[maxlen], input[maxlen], *nl;
12a15,16
>     if ((nl = strrchr(source, '\n')))
>         *nl = 0;

14c18,20
<   gets(destination, maxlen, stdin);
---
Quote:
>     fgets(destination, maxlen, stdin);
>     if ((nl = strrchr(destination, '\n')))
>         *nl = 0;

31c37
<   return;
---

Quote:
>     return 0;

  ** resulting code **

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define maxlen 120

int file_copy(char oldname[maxlen], char newname[maxlen]);

int main()
{

    char source[maxlen], destination[maxlen], input[maxlen], *nl;

    printf("Enter a source filename: ");
    fgets(source, maxlen, stdin);
    if ((nl = strrchr(source, '\n')))
        *nl = 0;
    printf("Enter destination filename: ");
    fgets(destination, maxlen, stdin);
    if ((nl = strrchr(destination, '\n')))
        *nl = 0;

    if (file_copy(source, destination) == 0)

        printf("Successful copying.");
    else
        fprintf(stderr, "\nError copying file.");
    printf("%d", file_copy(source, destination));

    /* ***************************** */
    /* this allows system operations */
    /* ***************************** */

    printf("\nInput desired system command, blank to exit\n");
    fgets(input, maxlen, stdin);
    system(input);

    return 0;

Quote:
}                               /* end main */

      /* write data to new  file */
int file_copy(char oldname[maxlen], char newname[maxlen])
{
    FILE *fpold, *fpnew;
    int c;
    /* open source file */
    if ((fpold = fopen(oldname, "rb")) == NULL)
        return -1;

    /* open destination file */
    if ((fpnew = fopen(newname, "wb")) == NULL)

        return -1;

    /* copy file */
    while (!feof(fpold)) {
        c = fgetc(fpold);
        fputc(c, fpnew);

    }

    fclose(fpold);
    fclose(fpnew);

    return 0;

Quote:
}                               /* end function */

/* vi: set cindent ts=4 sw=4 et tw=72: */

Quote:

> #include <stdio.h>
> #include <stdlib.h>
> #define maxlen 120
> int file_copy(char oldname[maxlen],char newname[maxlen]);

> int main()
> {

>      char ch,source[maxlen],destination[maxlen],input[maxlen];

>      printf("Enter a source filename: ");
>      fgets(source,maxlen,stdin);
>      printf("Enter destination filename: ");
>      gets(destination,maxlen,stdin);

>       if (file_copy(source,destination)==0)

>           printf("Successful copying.");
>        else
>           fprintf(stderr,"\nError copying file.");
>           printf("%d",file_copy(source,destination));

>          /* ***************************** */
>          /* this allows system operations */
>          /* ***************************** */

>          printf("\nInput desired system command, blank to exit\n");
>          fgets(input,maxlen,stdin);
>          system(input);

>       return;
>  }//end main

>       /* write data to new  file */
> int file_copy(char oldname[maxlen],char newname[maxlen])
> {
>      FILE *fpold,*fpnew;
>      int c;
>         /*open source file*/
>       if ((fpold = fopen(oldname,"rb"))==NULL)
>              return -1;

>          /*open destination file*/
>       if ((fpnew = fopen(newname,"wb"))==NULL)

>              return -1;

>           /*copy file*/
>          while (!feof(fpold))
>                {
>                     c=fgetc(fpold);
>                     fputc(c,fpnew);

>              }

>          fclose(fpold);
>          fclose(fpnew);

>         return 0;
> }//end function

--

What one knows is, in youth, of little moment; they know enough who
know how to learn. - Henry Adams

A thick skin is a gift from God. - Konrad Adenauer
__________________________________________________________
Fight spam now!
Get your free anti-spam service: http://www.brightmail.com



Sun, 25 Aug 2002 03:00:00 GMT  
 fgets()


Quote:
> When I excecute this code using the fgets statements on lines 14-18
> (approx). The code doesn't function properly, but when I use gets()
it's
> fine, but I get advised against using this method. The fgets() later
on
> causes no problems, anyone help?

I haven't studied your code in detail, but I notice you are using the
fgets function to get a filename. fgets will include the newline
character in the char array when it has room to do so, so you might be
inputing a filename like this: "myfile.c\n". When you use this in fopen
to open "myfile.c" the fopen will fail as "myfile.c\n" will not be
found. You need to strip the newline char from this array.

One solution is to write a function to do this:

#include <stdin.h>
#include <string.h>

char *getstring(char *str,size_t size) {
   char *s;
   int c;

   fgets(str,size,stdin);
   if((s = strchr(str,"\n")) != NULL) *s = '\0';
   else while((c = getchar()) != '\n' && c != EOF);
   return s;
   }

Then in main make the call

Quote:

> #include <stdio.h>
> #include <stdlib.h>
> #define maxlen 120
> int file_copy(char oldname[maxlen],char newname[maxlen]);

> int main()
> {

>      char ch,source[maxlen],destination[maxlen],input[maxlen];

>      printf("Enter a source filename: ");
>      fgets(source,maxlen,stdin);

instead of the above fgets statement use.
getstring(source, sizeof source);

--
Al Bowers

GIBCO Labs.
Tampa FL. USA.

Sent via Deja.com http://www.deja.com/
Before you buy.



Sun, 25 Aug 2002 03:00:00 GMT  
 fgets()
The behavior of fgets() vs. gets() regarding newlines has been covered, but
I haven't seen anyone point out that you're misusing feof().  feof() does
not return true until after a failed attempt to read the file.

On Wed, 8 Mar 2000 17:48:18 -0000, "Ian"
...

Quote:
>          /*copy file*/
>         while (!feof(fpold))
>               {
>                    c=fgetc(fpold);
>                    fputc(c,fpnew);

>             }

At the end of the file, fgetc() will return EOF, and you'll end up writing
the char equivalent of EOF to the new file, making the copied file one char
longer than the source file.  The more usual C idiom is

    while((c = fgetc(fpold)) != EOF)
        fputc(c, fpnew);
--



Sun, 25 Aug 2002 03:00:00 GMT  
 fgets()

Quote:

> When I excecute this code using the fgets statements on lines 14-18
> (approx). The code doesn't function properly, but when I use gets() it's
> fine, but I get advised against using this method. The fgets() later on
> causes no problems, anyone help?

What do you mean "doesn't function properly"? I see a couple of problems
with the code that may be causing the malfunction.

1.)  Use function fflush after the prompts. See the com.lang.c faq (address
is in my signature) question 12.4

2) Do not use function gets, function fgets will work safely if you use it
correctly.

3) function fgets will, in most cases, will include the newline character
when you input. Since you are using this input for a filename and since most
filenames do not have a newline char appended, you will need to remove the
newline char from the array. Otherwise, your fopen statement will fail
because of a "file not found".

4) in function file_copy, the while loop looks suspicious. Consider:
   while((c = fgetc(fpood)) != EOF) {

Quote:

> #include <stdio.h>
> #include <stdlib.h>
> #define maxlen 120
> int file_copy(char oldname[maxlen],char newname[maxlen]);

> int main()
> {

>      char ch,source[maxlen],destination[maxlen],input[maxlen];

char *s;
int ch

Quote:

>      printf("Enter a source filename: ");

fflush(stdout); /* add after each prompt */

Quote:

>      fgets(source,maxlen,stdin);

/* to remove a possilble newline char, include header string.h, a char *s
variable, an int varialbe, and the following code */

if((s = strchr(source,'\n')) != NULL) *s = '\0'; /* overwrites the newline
character */
else while((ch = getchar()) != '\n' && ch != EOF); /* clears the stdin
stream of leftover char */

==================
You can write a function to do this:

char *getstring(char *str, size_t size) {
   char *s;
   int ch;

   if(!str) return NULL;
   fgets(str,size,stdin);
   if((s = getchar()) != NULL) *s = '\0';
   else while((ch = getchar()) != '\n' && ch != EOF);
   return str;
   }

Then in main, in place of the fgets calls use function getstring.

getstring(source, sizeof source);

--
Al Bowers
Tampa, FL  USA

http://www.gate.net/~abowers/



Mon, 02 Sep 2002 03:00:00 GMT  
 
 [ 6 post ] 

 Relevant Pages 

1. annoying fgets problem <fgets>

2. fgets()/buffer problem - should I use fgets(), printf() & co at all?

3. Need assitance in using fgets()

4. fgets reading a configuration file: compiles OK but output wrong

5. fgets reading a configuration file:

6. fgets vs scanf

7. fgets help

8. Using getchar() instead of fgets or scanf

9. fgets and fgetc ?

10. fgets/sscanf

11. Length of string read by fgets

12. Problems with fgets and reading in a number

 

 
Powered by phpBB® Forum Software