FILE objects

Collapse
This topic is closed.
X
X
 
  • Time
  • Show
Clear All
new posts
  • Bill Cunningham

    #1

    FILE objects

    I've been trying to fopen a file, fread it and fwrite it to another file
    or stdout while having k&r2 at hand and having no luck. The appendix seems
    to be very vague on the FILE struct components.

    Bill


  • Christopher Benson-Manica

    #2
    Re: FILE objects

    Bill Cunningham <nospam@nspam.n et> spoke thus:
    [color=blue]
    > I've been trying to fopen a file, fread it and fwrite it to another file
    > or stdout while having k&r2 at hand and having no luck. The appendix seems
    > to be very vague on the FILE struct components.[/color]

    Let's see the code - I'm sure clc can help.

    --
    Christopher Benson-Manica | I *should* know what I'm talking about - if I
    ataru(at)cybers pace.org | don't, I need to know. Flames welcome.

    Comment

    • Gordon Burditt

      #3
      Re: FILE objects

      > I've been trying to fopen a file, fread it and fwrite it to another file[color=blue]
      >or stdout while having k&r2 at hand and having no luck. The appendix seems
      >to be very vague on the FILE struct components.[/color]

      It *SHOULD* be vague on the FILE struct components. Hands off!
      The stuff in there is system-specific and is likely to not be very
      helpful unless you really know how it works, in which case you
      probably wouldn't be having the above problem.

      When you call fopen(), do you check for whether it returns NULL?
      If fopen() returns NULL, do you call perror() or strerror() and
      then print the resulting string in a nice error message for the
      user/programmer? (Yes, I know fopen() is not guaranteed to set
      errno, but as long as it's not guaranteed to *NOT* set errno,
      printing the possibly irrelevant message is more useful for the
      programmer, or for the user who can report it to the programmer,
      to debugging than not printing it). You do need to realize that
      some error messages are not applicable, for example, "output.txt :
      not a typewriter" doesn't make a lot of sense, but "output.txt :
      permission denied" suggests a reason why the file couldn't be
      created.

      Did you fopen() the file in binary mode? Do you WANT to open the
      file in binary mode? If you are trying to fwrite() the contents
      of C types such as int, long, float, double, or struct, chances are
      you want to open an output file in binary mode, and when you try
      to read it back in, you also want it opened in binary mode. On the
      other hand, if you're just going to fwrite() blobs of text, maybe
      you want the file open in text mode.

      Do you check the return values from fread() and fwrite()? Have you
      tried using a hex dump utility on the output file, and compared the
      file contents with what you expect to be in there? Does your code
      realize that fread() may well read in the data in chunks that don't
      correspond with the chunks that you wrote in the first place?

      Gordon L. Burditt

      Comment

      • Malcolm

        #4
        Re: FILE objects


        "Bill Cunningham" <nospam@nspam.n et> wrote in message[color=blue]
        > I've been trying to fopen a file, fread it and fwrite it to another[/color]
        file[color=blue]
        > or stdout while having k&r2 at hand and having no luck. The
        > appendix seems to be very vague on the FILE struct components.
        >[/color]
        FILE is an opaque structure. If you access the members then you are doing
        something wrong.

        Try the following

        /*
        a copy utility
        */
        #include <stdio.h>
        #include <stdlib.h>
        int main(int argc, char **argv)
        {
        FILE *fpin;
        FILE *fpout;
        int ch;
        fpin = fopen(argv[1], "rb");
        if(!fpin)
        {
        printf("Can't open %s for reading\n", argv[1]);
        exit(EXIT_FAILU RE);
        }

        fpout = fopen(argv[2], "wb");
        if(!fpout)
        {
        printf("Can't open %s for writing\n", argv[2]);
        exit(EXIT_FAILU RE);
        }

        /* the loop */
        while( (ch = fgetc(fpin)) != EOF)
        fputc(ch, fpout);

        /* claen up and go home */
        fclose(fpin);
        if( fclose(fpout) != 0)
        {
        printf("Error closing %s\n", argv[2]);
        exit(EXIT_FAILU RE);
        }

        return 0;
        }



        Comment

        • Bill Cunningham

          #5
          Re: FILE objects


          [color=blue]
          >
          > Let's see the code - I'm sure clc can help.[/color]

          printf("EnterFi lename-> ");
          fflush(stdout);
          char fname;
          scanf("%c",&fna me);
          FILE *fp;
          fopen(fname,30, 30,fp);
          fread(fname,"rb ");
          fwrite("file",3 0,30,fp);
          fclose(fp);
          Now I know there should be some casts here. I find k&r2's function
          prototypes hard to read. Not the functions explained with bodies in the
          book. But these file functions aren't described in detail. I don't
          understand the parameters by looking at prototypes and no example of how to
          write the code.

          Bill


          Comment

          • Eric Sosman

            #6
            Re: FILE objects

            Bill Cunningham wrote:[color=blue]
            >
            > I've been trying to fopen a file, fread it and fwrite it to another file
            > or stdout while having k&r2 at hand and having no luck. The appendix seems
            > to be very vague on the FILE struct components.[/color]

            The vagueness is intentional, since the details of the
            FILE object are not supposed to concern you, and indeed are
            different from one implementation to the next.

            None of the Standard library functions accept or return
            `FILE' objects anyhow: they all deal in `FILE*' pointers to
            such objects. Have you mixed up the pointer and the pointee?

            --
            Eric.Sosman@sun .com

            Comment

            • Marcin Hoppe

              #7
              Re: FILE objects

              Bill Cunningham wrote:[color=blue][color=green]
              >>Let's see the code - I'm sure clc can help.[/color]
              >
              >
              > printf("EnterFi lename-> ");
              > fflush(stdout);
              > char fname;
              > scanf("%c",&fna me);
              > FILE *fp;
              > fopen(fname,30, 30,fp);
              > fread(fname,"rb ");
              > fwrite("file",3 0,30,fp);
              > fclose(fp);
              > Now I know there should be some casts here. I find k&r2's function
              > prototypes hard to read. Not the functions explained with bodies in the
              > book. But these file functions aren't described in detail. I don't
              > understand the parameters by looking at prototypes and no example of how to
              > write the code.[/color]

              You have a problem with reading the filename. You declared it as a
              single character, not as an array of characters (string). The second
              problem I noticed is that you've misused fopen and fwrite functions.
              After some improvements your code should be similar to this:

              #include <stdio.h>

              int main() {
              /* File object */
              FILE *fp = NULL;
              /* File name */
              char fname[256];
              /* Some buffer to read, 30 bytes (on my computer) */
              char rd_buf[30];

              /* Nice prompt :) */
              printf("EnterFi lename->");
              fflush(stdout);

              /* This way you get the whole string */
              scanf("%s", fname);

              /* Open the file for reading in binary mode */
              fp = fopen(fname, "rb");

              /* Check if file was opened successfully */
              if(fp != NULL) {
              /* Read some bytes from the opened file */
              /* Data is read to the rd_buf buffer */
              /* Amount of data read is computed here, */
              /* so you don't need to worry if you change */
              /* size of the buffer */
              fread( (void *) rd_buf, sizeof(char),
              sizeof(rd_buf) / sizeof(rd_buf[0]), fp);
              }

              /* Close the file */
              fclose(fp);

              return 0;
              }

              I hope I've helped.

              --
              E-mail: marcinhoppe@poc zta.onet.pl
              WWW: http://marcinhoppe.republika.pl
              GaduGadu IM: 2222891
              Looking for a job as a software developer.

              Comment

              • Bill Cunningham

                #8
                Re: FILE objects

                [color=blue]
                > Try the following
                >
                > /*
                > a copy utility
                > */
                > #include <stdio.h>
                > #include <stdlib.h>
                > int main(int argc, char **argv)
                > {
                > FILE *fpin;
                > FILE *fpout;
                > int ch;
                > fpin = fopen(argv[1], "rb");
                > if(!fpin)
                > {
                > printf("Can't open %s for reading\n", argv[1]);
                > exit(EXIT_FAILU RE);
                > }
                >
                > fpout = fopen(argv[2], "wb");
                > if(!fpout)
                > {
                > printf("Can't open %s for writing\n", argv[2]);
                > exit(EXIT_FAILU RE);
                > }
                >
                > /* the loop */
                > while( (ch = fgetc(fpin)) != EOF)
                > fputc(ch, fpout);
                >
                > /* claen up and go home */
                > fclose(fpin);
                > if( fclose(fpout) != 0)
                > {
                > printf("Error closing %s\n", argv[2]);
                > exit(EXIT_FAILU RE);
                > }
                >
                > return 0;
                > }
                >[/color]
                I've never used stdlib. Is it the standard utilities header? That
                parameter in main I've never quite understood either. I know main(void) but
                that's it. How many parameters can main take.

                Bill



                Comment

                • Bill Cunningham

                  #9
                  Re: FILE objects

                  Have you mixed up the pointer and the pointee?[color=blue]
                  >[/color]

                  Quite probably. I don't know when I need int var or int *var.

                  Bill


                  Comment

                  • Gordon Burditt

                    #10
                    Re: FILE objects

                    >> Let's see the code - I'm sure clc can help.[color=blue]
                    >
                    > printf("EnterFi lename-> ");
                    > fflush(stdout);
                    > char fname;[/color]
                    In C89, this is not a valid place for a C variable declaration.
                    A filename is a NUL-terminated array of characters. One
                    character, including the terminating NUL, is not enough.
                    Try:
                    char fname[10240]; /* hope this is long enough */
                    [color=blue]
                    > scanf("%c",&fna me);[/color]
                    A C string should use %s, not %c.[color=blue]
                    > FILE *fp;[/color]
                    In C89, this is not a valid place for a C variable declaration.[color=blue]
                    > fopen(fname,30, 30,fp);[/color]

                    Check the return value of fopen()!! Also, fopen() has two arguments,
                    not 4.
                    [color=blue]
                    > fread(fname,"rb ");[/color]

                    Check the return value of fread(). You seem to have gotten the
                    arguments to fopen() and fread() switched here.
                    [color=blue]
                    > fwrite("file",3 0,30,fp);[/color]
                    Check the return value of fwrite(). Also, the first argument is
                    a buffer containing the data to write, NOT the file name.
                    [color=blue]
                    > fclose(fp);[/color]
                    [color=blue]
                    >Now I know there should be some casts here. I find k&r2's function
                    >prototypes hard to read. Not the functions explained with bodies in the
                    >book. But these file functions aren't described in detail. I don't
                    >understand the parameters by looking at prototypes and no example of how to
                    >write the code.[/color]

                    It's obvious you need to do a lot of manual reading before trying
                    to write this code. Maybe you should get something more at a tutorial
                    level; K&R tends to be more of a reference manual for people who
                    know this stuff to look up the details rather than trying to teach
                    the basics.

                    Gordon L. Burditt

                    Comment

                    • Malcolm

                      #11
                      Re: FILE objects


                      "Bill Cunningham" <nospam@nspam.n et> wrote in message[color=blue]
                      >
                      > I've never used stdlib. Is it the standard utilities header?
                      >[/color]
                      Yes. Here it is used for the exit() function and the EXIT_FAILURE value that
                      we use to indicate that the program hasn't worked for some reason. You also
                      need stdlib for malloc().[color=blue]
                      >
                      > That parameter in main I've never quite understood either. I know
                      > main(void) but that's it. How many parameters can main take.
                      >[/color]
                      main() can either be void, or it can take 2 parameters, argc and argv. argc
                      tells you how many words were typed on the command line, argv is an array of
                      strings. Conventionally, argv[0] is the name of the program. If you typed
                      copy.exe myfile.x newfile.x

                      argv[0] = copy.exe
                      argv[1] = myfile.x
                      argv[2] = newfile.x

                      (Incidentally there is a bug in my program. Really we should check that argc
                      == 3 and report an error if it does not. It might crash if invoked with only
                      one filename.)


                      Comment

                      • Thomas stegen

                        #12
                        Re: FILE objects

                        Bill Cunningham wrote:[color=blue]
                        > Have you mixed up the pointer and the pointee?
                        >
                        >
                        > Quite probably. I don't know when I need int var or int *var.[/color]

                        My suggestion to you is to stay completely away from
                        pointers and file operations until you have a better grasp
                        of the language. Do some calculations using loops and
                        whatnot until you are sure you understand how variables work.
                        Then do the same using function calls. Then maybe add in
                        some structs and after that start using pointers. Build slowly,
                        and only when you are sure you have the foundation in place
                        move on. If you have trouble with the difference between
                        int var and int *var I suggest you stay away from FILE
                        objects for now.

                        --
                        Thomas.

                        Comment

                        • Eric Sosman

                          #13
                          Re: FILE objects

                          Bill Cunningham wrote:[color=blue]
                          >[color=green]
                          > >
                          > > Let's see the code - I'm sure clc can help.[/color]
                          >
                          > printf("EnterFi lename-> ");
                          > fflush(stdout);
                          > char fname;
                          > scanf("%c",&fna me);
                          > FILE *fp;
                          > fopen(fname,30, 30,fp);
                          > fread(fname,"rb ");
                          > fwrite("file",3 0,30,fp);
                          > fclose(fp);
                          > Now I know there should be some casts here. [...][/color]

                          "This isn't right. It isn't even wrong." It's certainly
                          beyond the power of casts to correct.
                          [color=blue]
                          > I find k&r2's function
                          > prototypes hard to read. Not the functions explained with bodies in the
                          > book. But these file functions aren't described in detail. I don't
                          > understand the parameters by looking at prototypes and no example of how to
                          > write the code.[/color]

                          You'll notice that Christopher asked you for *the* code,
                          not just for *some* code. Please post *the* code, not a
                          sawed-off bleeding chunk, nor yet a paraphrase: *the* code,
                          cut'n'pasted straight from your editor into the message.

                          As it stands, we're all left guessing about what's going
                          on. You probably #include'd <stdio.h> because otherwise
                          the compiler would have barfed on the undefined identifier
                          `stdout' -- but if <stdio.h> was i#include'd the compiler
                          would have barfed on the incorrect arguments to fopen() and
                          fread(). Clearly you have done something very peculiar indeed,
                          and nobody's likely to give you a good diagnosis until you
                          reveal what you've done.

                          Or (sudden sad disillusionment ) is it possible that you
                          have in fact written no code at all, and you're simply trying
                          to trick c.l.c. into writing your homework assignment for you?
                          Say it ain't so, Joe.

                          --
                          Eric.Sosman@sun .com

                          Comment

                          • Bill Cunningham

                            #14
                            Re: FILE objects

                            > You have a problem with reading the filename. You declared it as a[color=blue]
                            > single character, not as an array of characters (string). The second
                            > problem I noticed is that you've misused fopen and fwrite functions.
                            > After some improvements your code should be similar to this:
                            >
                            > #include <stdio.h>
                            >
                            > int main() {
                            > /* File object */
                            > FILE *fp = NULL;
                            > /* File name */
                            > char fname[256];
                            > /* Some buffer to read, 30 bytes (on my computer) */
                            > char rd_buf[30];
                            >
                            > /* Nice prompt :) */
                            > printf("EnterFi lename->");
                            > fflush(stdout);
                            >
                            > /* This way you get the whole string */
                            > scanf("%s", fname);
                            >
                            > /* Open the file for reading in binary mode */
                            > fp = fopen(fname, "rb");
                            >
                            > /* Check if file was opened successfully */
                            > if(fp != NULL) {
                            > /* Read some bytes from the opened file */
                            > /* Data is read to the rd_buf buffer */
                            > /* Amount of data read is computed here, */
                            > /* so you don't need to worry if you change */
                            > /* size of the buffer */
                            > fread( (void *) rd_buf, sizeof(char),
                            > sizeof(rd_buf) / sizeof(rd_buf[0]), fp);
                            > }
                            >
                            > /* Close the file */
                            > fclose(fp);
                            >
                            > return 0;
                            > }
                            >
                            > I hope I've helped.
                            >[/color]
                            Those sizeof's in your code. Do they report to size_t ?

                            Bill


                            Comment

                            • Marcin Hoppe

                              #15
                              Re: FILE objects

                              Bill Cunningham wrote:[color=blue]
                              >
                              > Those sizeof's in your code. Do they report to size_t ?
                              >[/color]

                              The sizeof operator returns the size of its argument. Its "unit" is the
                              size of char (on x86 platform it is usually 1 byte) and the return type
                              is size_t. It's written in K&R :).

                              --
                              E-mail: marcinhoppe@poc zta.onet.pl
                              WWW: http://marcinhoppe.republika.pl
                              GaduGadu IM: 2222891
                              Looking for a job as a software developer.

                              Comment

                              Working...