printing a text file

This is a discussion on printing a text file within the C Programming forums, part of the General Programming Boards category; Code: #include <stdio.h> int main() { FILE *fp; char *ficheiro; char *buffer; int i=0; printf("Please enter the file directory: "); ...

  1. #1
    j_spinto
    Guest

    printing a text file

    Code:
    #include <stdio.h>
    
    int main() {
        FILE *fp;
        char *ficheiro;
        char *buffer;
        int i=0;
        printf("Please enter the file directory: ");
        gets(ficheiro);
        fp=fopen(ficheiro,"r");
        while ((buffer[i]=fgetc(fp))==EOF)
              i++;
        printf("%s",buffer);
        fclose(fp);
        return 0;
    }
    The program gives me an error :S

  2. #2
    Registered User
    Join Date
    Apr 2005
    Posts
    134
    here here...

    First never use gets() use fgets(). Search through forum to find some posts which has links which explains why?

    Second Following 2
    Code:
    char *ficheiro;
    char *buffer;
    are just pointer who points nowhere...You need to allocate memory to them (using malloc() or calloc()) before you dereference them. Without it, its a sure crash. Why? becuase they point nowhere, or someone else's (some other program's) memory region. When you try to store any data in those region you OS will scream (segmentation fault or memory access violation) and your program will crash there itself.

  3. #3
    Just Lurking Dave_Sinkula's Avatar
    Join Date
    Oct 2002
    Posts
    5,006
    7. It is easier to write an incorrect program than understand a correct one.
    40. There are two ways to write error-free programs; only the third one works.*

  4. #4
    j_spinto
    Guest
    and so I can give a value to ficheiro variable without allocating needlessly unknown space, how can i do like this correctly:
    char ficheiro[] = gets();

  5. #5
    Just Lurking Dave_Sinkula's Avatar
    Join Date
    Oct 2002
    Posts
    5,006
    Quote Originally Posted by j_spinto
    and so I can give a value to ficheiro variable without allocating needlessly unknown space
    Why? Premature optimization?

    [edit]Try this thread.
    Last edited by Dave_Sinkula; 06-24-2005 at 04:22 PM.
    7. It is easier to write an incorrect program than understand a correct one.
    40. There are two ways to write error-free programs; only the third one works.*

  6. #6
    I typecast anyway.
    Join Date
    Jun 2005
    Posts
    25
    It sounds like he's used to other languages which do not require you to set a maximum string size initially. This is a familiar feeling, I've been there too.

    The problem is, gets() and fgets() do not allocate their own space. Each takes a pointer to a character array and puts its data there.

    So you need to either declare your variable like so:
    Code:
    char ficheiro[100];
    Or leave your declaration as it is and allocate the memory like so:
    Code:
    ficheiro = malloc (100);
    fgets (ficheiro, 100, stdin);
    ...
    free (ficheiro);
    This way, ficheiro has its own space and fgets() will write to that space.
    Last edited by Raptor007; 06-24-2005 at 10:46 PM. Reason: removed gets()

  7. #7
    and the hat of wrongness Salem's Avatar
    Join Date
    Aug 2001
    Location
    The edge of the known universe
    Posts
    32,338
    > This way, ficheiro has its own space and gets will write to that space.
    It's one thing to go around ignoring everyone elses advice, but when you start dishing out your own dangerous misguided ideas as well, that's a whole new ball game.
    If you dance barefoot on the broken glass of undefined behaviour, you've got to expect the occasional cut.
    If at first you don't succeed, try writing your phone number on the exam paper.
    I support http://www.ukip.org/ as the first necessary step to a free Europe.

  8. #8
    I typecast anyway.
    Join Date
    Jun 2005
    Posts
    25
    Quote Originally Posted by Salem
    > This way, ficheiro has its own space and gets will write to that space.
    It's one thing to go around ignoring everyone elses advice, but when you start dishing out your own dangerous misguided ideas as well, that's a whole new ball game.
    What is wrong with you, and what are you talking about?
    I even left out the cast, just for you.

    Btw, it was nice of you to post to this guy's thread just to flame me and not even let him know WHAT it was about my ideas you didn't like or give any alternative suggestions. I'm sure he appreciates the input.
    Last edited by Raptor007; 06-24-2005 at 10:25 PM. Reason: censored

  9. #9
    ATH0 quzah's Avatar
    Join Date
    Oct 2001
    Posts
    14,826
    Well for starters, you ignored the first reply, which was that gets is a bad function. You also ignored the FAQ link, which shows a much better way to get input.


    Quzah.
    Hope is the first step on the road to disappointment.

  10. #10
    Just Lurking Dave_Sinkula's Avatar
    Join Date
    Oct 2002
    Posts
    5,006
    Anyone who posts code using gets, or worse -- demonstrating the use of gets -- has earned a little abuse. It's a sign that one doesn't "get it" and needs to spend several minutes or hours in the FAQ until one does.
    7. It is easier to write an incorrect program than understand a correct one.
    40. There are two ways to write error-free programs; only the third one works.*

  11. #11
    I typecast anyway.
    Join Date
    Jun 2005
    Posts
    25
    I'm sorry about that, you're right that I shouldn't have used gets in my example. My post was mainly supposed to show that he needs memory allocated to use any such function (giving some code to nkhambal's idea).

  12. #12
    j_spinto
    Guest
    Code:
    #include <stdio.h>
    
    int main() {
        FILE *fp;
        printf("Insira a directória do ficheiro: ");
        char *ficheiro;
        ficheiro=malloc(100);
        fgets(ficheiro,100,stdin);
        free(ficheiro);
        char buf[BUFSIZ];
        int i=0;
        fp=fopen(ficheiro,"r");
        while ((buf[i]=fgetc(fp))!=EOF)
              i++;
        printf("%s",buf);
        fclose(fp);
        return 0;
    }
    now what's wrong with this ?

  13. #13
    and the hat of wrongness Salem's Avatar
    Join Date
    Aug 2001
    Location
    The edge of the known universe
    Posts
    32,338
    There are many things wrong.

    1. It isn't written in C, C doesn't support (yet) mixed declarations and statements.
    2. you don't prototype malloc by including stdlib.h
    3. you free() your input before you've had a chance to use the string to open a file.
    4. there's no error checking in any of your code.
    5. your EOF test will likely fail because the inner assignment casts your actual EOF to a char
    6. your buf has no \0 to terminate the string (when you print it with %s)

    Consider
    Code:
    #include <stdio.h>
    #include <string.h>
    
    int main() {
      char buf[BUFSIZ],ficheiro[100];
      int i=0;
      FILE *fp;
    
      printf("Insira a directória do ficheiro: ");
      fflush(stdout); /* make sure the prompt appears */
    
      if ( fgets(ficheiro,sizeof(ficheiro),stdin) != NULL ) {
        char *nl = strchr(ficheiro,'\n');
        if ( nl != NULL ) *nl = '\0';  /* remove the newline, if present */
        
        fp=fopen(ficheiro,"r");
        if ( fp != NULL ) {
          int ch;
          while ( i < BUFSIZ-1 && (ch=fgetc(fp)) != EOF ) {
            buf[i++] = (char)ch;
          }
          buf[i] = '\0';
          printf("%s",buf);
          fclose(fp);
        }
      }
      return 0;
    }
    If you dance barefoot on the broken glass of undefined behaviour, you've got to expect the occasional cut.
    If at first you don't succeed, try writing your phone number on the exam paper.
    I support http://www.ukip.org/ as the first necessary step to a free Europe.

  14. #14
    j_spinto
    Guest
    thanks

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. A development process
    By Noir in forum C Programming
    Replies: 37
    Last Post: 07-10-2011, 10:39 PM
  2. Formatting a text file...
    By dagorsul in forum C Programming
    Replies: 12
    Last Post: 05-02-2008, 03:53 AM
  3. Unknown Memory Leak in Init() Function
    By CodeHacker in forum Windows Programming
    Replies: 3
    Last Post: 07-09-2004, 09:54 AM
  4. help printing text file
    By Unregistered in forum C Programming
    Replies: 6
    Last Post: 05-19-2002, 10:33 PM
  5. Problem when printing to text file
    By sissoko in forum Windows Programming
    Replies: 2
    Last Post: 01-20-2002, 05:26 AM

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21