Opening a file and then printing the output?

This is a discussion on Opening a file and then printing the output? within the C Programming forums, part of the General Programming Boards category; Hello, I'm trying to write a program that prompts the user to enter a filename, open that filename (3 paragraph ...

  1. #1
    Registered User
    Join Date
    Sep 2006
    Posts
    10

    Opening a file and then printing the output?

    Hello, I'm trying to write a program that prompts the user to enter a filename, open that filename (3 paragraph story) and then print it out as it's shown in the input file. Theres a few parts that make it a little more difficult than that. I'm fine with prompting the user, storing the filename in a string, opening the file via the string name, and checking to make sure the file input is correct (code below).

    Now, I need to scan through the input, determine how many characters it is and declare a string of that size, we aren't allowed to just declare a string of a set size we know would be big enough. I've heard the function malloc() will determine the overall length, and then I can just assign that to a variable, but I'm not too sure how the function works, I'm still messing with that. The other part I'm stumped on is how to print the output so it looks just like the input file. For the code I have, I just declared a string with a size of 500 to see if I could get it right, all of the text is just clumped toether, there are no spaces in between and it doesn't start a new line as is shown on the input file. Any tips, help, or suggestions would be greatly appreciated, thanks!

    Code:
    #include <stdio.h>
    #include <stdlib.h>
    #include <string.h>
    
    int main()
    {
    
       FILE *in_file;
       char dataFile[20];
       char story[500];
       int i;
    
       printf("Enter the file you wish to open  ");
       scanf("%s", dataFile);
    
       in_file = fopen(dataFile, "r");
    
    
       if (in_file == NULL)
       {
          printf ("An Error occured while attempting to open the file\n");
          exit (-1);
       }
    
       for (i = 0; i < 500; i++)
       {
          fscanf(in_file, "%s", &story[i]);
          printf("%s", &story[i]);
       }
      
    
    
       fclose(in_file);
    
       return 0;
    }

  2. #2
    {Jaxom,Imriel,Liam}'s Dad Kennedy's Avatar
    Join Date
    Aug 2006
    Location
    Alabama
    Posts
    1,065
    IMO, since you don't want to change the data, you only need to do a loop that will get one char at a time, OR, you could use a buffer and fgets() to grab chunks of data (just remember to put your '\0') at the end of your buffer and printf() the strings.

    Using scanf() on a file of this type is considered to be "bad". It also wouldn't display your story the same way you read it from the file, as it would remove any white space.

  3. #3
    Frequently Quite Prolix dwks's Avatar
    Join Date
    Apr 2005
    Location
    Canada
    Posts
    8,046
    Quote Originally Posted by Sholcomb1
    Now, I need to scan through the input, determine how many characters it is and declare a string of that size, we aren't allowed to just declare a string of a set size we know would be big enough. I've heard the function malloc() will determine the overall length, and then I can just assign that to a variable, but I'm not too sure how the function works, I'm still messing with that. The other part I'm stumped on is how to print the output so it looks just like the input file. For the code I have, I just declared a string with a size of 500 to see if I could get it right, all of the text is just clumped toether, there are no spaces in between and it doesn't start a new line as is shown on the input file. Any tips, help, or suggestions would be greatly appreciated, thanks!
    Googling for "malloc" leads to a page detailing the malloc() function. From http://www.opengroup.org/onlinepubs/...ns/malloc.html:
    void *malloc(size_t size);

    The malloc() function shall allocate unused space for an object whose size in bytes is specified by size and whose value is unspecified.

    Upon successful completion with size not equal to 0, malloc() shall return a pointer to the allocated space. If size is 0, either a null pointer or a unique pointer that can be successfully passed to free() shall be returned. Otherwise, it shall return a null pointer [CX] and set errno to indicate the error.
    In English, malloc() will allocate the number of bytes passed to it. This memory will not be set to anything, so you should set it to something yourself. It returns NULL on failure.

    To allocate enough memory for an int:
    Code:
    int *theint = malloc(sizeof(int));
    if(*theint) {
        *theint = 1;
        printf("%i\n", *theint);
        free(theint);
    }
    else  /* out of memory */ ;
    To allocate enough memory for ten ints, that is an array of ints:
    Code:
    int *intarray = malloc(10 * sizeof(int));
    
    if(*theint) {
        intarray[0] = intarray[2] = 5;
        free(intarray);
    }
    else  /* out of memory */ ;
    It's important to use sizeof(int) rather than a hard-coded value such as 4, because the size of an int might differ between compilers. The exception is a char; sizeof(char) is always 1, so you can leave it out.
    Code:
    char *memory = malloc(characters+1);  /* +1 for a NULL! */
    In order to hold an array of pointers to more memory (that is, a dynamically allocated array of pointers to more dynamically allocated memory), you could use something like this:
    Code:
    char **data;
    size_t x;
    
    data = malloc(lines * sizeof(char *));
    for(x = 0; x < lines; x ++) {
        data[x] = malloc(line_len[x] + 1);
    }
    
    /* use it */
    
    for(x = 0; x < lines; x ++) free(data[x]);
    free(data);
    For that, however, you'd need to know the lengths of all the lines in the file beforehand, and how many lines there actually are. You could read through it and determine this, but a better solution might be to resize the array of pointers to the lines to accomodate each new line, and allocate each line to a larger size to accomodate each new part of the line read in. You can do this with realloc().

    Also see CProgramming.com Tutorials: C File I/O and Binary File I/O.
    dwk

    Seek and ye shall find. quaere et invenies.

    "Simplicity does not precede complexity, but follows it." -- Alan Perlis
    "Testing can only prove the presence of bugs, not their absence." -- Edsger Dijkstra
    "The only real mistake is the one from which we learn nothing." -- John Powell


    Other boards: DaniWeb, TPS
    Unofficial Wiki FAQ: cpwiki.sf.net

    My website: http://dwks.theprogrammingsite.com/
    Projects: codeform, xuni, atlantis, nort, etc.

  4. #4
    CSharpener vart's Avatar
    Join Date
    Oct 2006
    Location
    Rishon LeZion, Israel
    Posts
    6,484
    I need to scan through the input, determine how many characters it is
    you can use ftell together with fseek to determine number of bytes in the file

    when read whole file (note that in the text mode the actually read number of bytes will be less due to /n/r conversion

    and when output the whole buffer (fread tells you how many bytes are actually read) to the new file as it is.

    you just need to worry to open two file in the same mode (both binary or both text)
    The first 90% of a project takes 90% of the time,
    the last 10% takes the other 90% of the time.

  5. #5
    Registered User
    Join Date
    Sep 2006
    Posts
    10
    Ok, thanks for the replies so far. Opening the file and then printing the output onto the screen as it's shown in the input file is good to go. I'm still not sure how to go about storing the file input into a string as it should be.

    after finding out how long the file input is I imagine I can just setup a for loop and set the counter to the last character storing each character into the string one at a time, I just can't get that part working right, storing it into the string.

  6. #6
    Fear the Reaper...
    Join Date
    Aug 2005
    Location
    Toronto, Ontario, Canada
    Posts
    625
    Have you ever looked at fgets ? That will essentially read one line of text from your file.
    Teacher: "You connect with Internet Explorer, but what is your browser? You know, Yahoo, Webcrawler...?" It's great to see the educational system moving in the right direction

Popular pages Recent additions subscribe to a feed

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