Thread: Reading in any File

  1. #1
    Registered User
    Join Date
    Mar 2012
    Posts
    4

    Reading in any File

    I'm brand new to c programming, and have an assignment that requires me to call on functions and manipulate data files etc.
    I decided to practice just to try and get the hang of reading in a single file and displaying at least a part of that file on the screen. The problem is when the program prompts me to type in the filename it is not able to find it.
    I have a hinting suspicion that it has something to do with how I've gone about trying to allow the user to input the filename.
    Any advice or help would be greatly appreciated as I am extremely new to all of this

    Code:
    #include <stdio.h>
    #include <stdlib.h>
        
    int main()
    {
        FILE *filep;
        char filename;
        float x, y;
         
         
         printf("Please enter name of file to be arranged and stored\n");
         scanf("%c",&filename);
         filep = fopen("&filename","r");
        
        if(filep != NULL)
         {
            fscanf(filep, "%f %f",&x, &y);
            printf("The first value is %f\nThe second value is %f",x,y);
            fclose(filep);
         }
         else 
         {
             printf("The file was unable to be opened, please try again");
         }
        return (0);
    }
    Thanks for your time and effort and sorry if the code is completely wrong :/

    cheers daeze

  2. #2
    C++ Witch laserlight's Avatar
    Join Date
    Oct 2003
    Location
    Singapore
    Posts
    28,413
    Quote Originally Posted by daeze
    I have a hinting suspicion that it has something to do with how I've gone about trying to allow the user to input the filename.
    This is likely to be wrong:
    Code:
    char filename;
    ... since a filename is likely to have more than one character. You should use an array of char instead, upon which this becomes wrong:
    Code:
    scanf("%c",&filename);
    You could fix it by using fgets instead, or by changing %c to %s (but you should then specify the number of characters).

    Once filename is an array of char, you can then change this:
    Code:
    filep = fopen("&filename","r");
    to:
    Code:
    filep = fopen(filename, "r");
    After all, you don't want to only open a file named "&filename", right?
    Quote Originally Posted by Bjarne Stroustrup (2000-10-14)
    I get maybe two dozen requests for help with some sort of programming or design problem every day. Most have more sense than to send me hundreds of lines of code. If they do, I ask them to find the smallest example that exhibits the problem and send me that. Mostly, they then find the error themselves. "Finding the smallest program that demonstrates the error" is a powerful debugging tool.
    Look up a C++ Reference and learn How To Ask Questions The Smart Way

  3. #3
    Registered User
    Join Date
    Sep 2006
    Posts
    8,868
    A hinting suspicion?? XD

  4. #4
    Registered User quickcoding's Avatar
    Join Date
    Mar 2012
    Location
    http://www.youtube.com/user/quickcoding/
    Posts
    3
    Yes never do this without an array of characters. Cut him some slack he's new XD

  5. #5
    Registered User
    Join Date
    Mar 2012
    Posts
    4
    Okay thanks for your help I have fixed the faults according to what you suggested and the is what it comes up with
    Code:
    Please enter name of file to be arranged and stored
    sp500.dat
    Program received signal:  “SIGABRT”.sharedlibrary 
    apply-load-rules all(gdb) 
    Which is better than failing to open anything but still not what I was hoping for. I researched fgets and not quite sure what it does or how to use it, but If you believe it is a better approach I will give it a go here is the revised code:
    Code:
    #include <stdio.h>
    #include <stdlib.h>
    	
    int main()
    {
    	FILE *filep;
    	char filename[8];
    	float x, y;
    	 
    	 
    	 printf("Please enter name of file to be arranged and stored\n");
    	 scanf("%s",filename);
    	 filep = fopen(filename,"r");
    	
    	if(filep != NULL)
    	 {
    		fscanf(filep, "%f %f",&x, &y);
    		printf("The first value is %f\nThe second value is %f",x,y);
    		fclose(filep);
    	 }
    	 else 
    	 {
    		 printf("The file was unable to be opened, please try again");
    	 }
    	return (0);
    }
    Also, I was wondering how to make it so 'any' file could be opened no matter how many characters in the name? is that what the 'fgets' function does? or should i create a variable for the character array?Again thanks heaps for your time and sorry for my noobishness :/cheers daeze

  6. #6
    Registered User
    Join Date
    Feb 2012
    Posts
    117
    I'm still a noobie to C as well. Correct me on anything if I'm wrong guys! Only been doing this since January. My past 4 or so assignments have been dealing with files and plenty more.I'm not sure of another way than dynamic memory allocation to get a different size for the filename. If you're not worried about that just put a reasonable size in the brackets for filename.
    I researched fgets and not quite sure what it does or how to use it
    fgets - C++ Reference fgets has 3 parts and looks like this
    Code:
    fgets(string, number_of_characters_read, pointer_to_file)
    it uses the pointer to the file to store that line into your character of strings (which in the code I put is "buffer"). The middle part is the number of characters it reads in that string (which is why I always just put sizeof(buffer)).Here's what I came up with for your code. Worked on my computer. But like I said, I'm still new. I'd take any advice from the people above me first!
    Code:
    #include <stdio.h>#include <stdlib.h>
         
    int main()
    {
        FILE *filep;
        char filename[50];  //Defines up to how many characters in the filename
        char buffer[50];    //Stores the data in each line in buffer
        float x, y;
          
         printf("Please enter name of file to be arranged and stored\n");
         scanf("%s",&filename);
         
         //Opens the file
        if ( (filep = fopen(filename, "r")) == NULL )
        {
         printf("Couldn't open file\n");
         exit(1); 
        } 
         //Reads the file line by line
        while( fgets(buffer, sizeof(buffer), filep))
         {
            sscanf(buffer,"%f %f", &x, &y);
            printf("The first value is %f\nThe second value is %f\n",x,y);
            getchar();
         }
        fclose(filep); 
    return (0);
    }

  7. #7
    Registered User ledow's Avatar
    Join Date
    Dec 2011
    Posts
    435
    Code:
    sp500.dat
    char filename[8];
    Spot the deliberate mistake. But I'm sure it's not the only one.

    - Compiler warnings are like "Bridge Out Ahead" warnings. DON'T just ignore them.
    - A compiler error is something SO stupid that the compiler genuinely can't carry on with its job. A compiler warning is the compiler saying "Well, that's bloody stupid but if you WANT to ignore me..." and carrying on.
    - The best debugging tool in the world is a bunch of printf()'s for everything important around the bits you think might be wrong.

  8. #8
    Registered User
    Join Date
    Mar 2012
    Posts
    4
    Quote Originally Posted by ledow View Post
    Code:
    sp500.dat
    char filename[8];
    Spot the deliberate mistake. But I'm sure it's not the only one.
    Obviously I'm very new because i thought that if I wanted 9 characters I needed to include '0' so a character array of [8] would give me the 9 characters i need. My friend from class however pointed out that this is not the case so I have since fixed it.

    Thanks very much for your help mgracecar! Theres some language in your code that I am studying to get a grip of what you did, so it was very informative I too tried it and it originally didnt work. After hours of frustration i decided to open a new file in xcode and try again for scratch. I also changed the path of the executable code and repasted your code in. It worked a treat and since has worked for all my other code, so I think it was just a permission in the previous file that was causing all the trouble!

    My job now is to put the data from the file into two arrays name x[] and y[], Ill keep you posted on how i go and will probably need some more friendly advice after I've had a good crack at it thanks to all who have offered your time and support. Much appreciated

    cheers 'A very relieved' daeze

  9. #9
    Registered User ledow's Avatar
    Join Date
    Dec 2011
    Posts
    435
    Quote Originally Posted by daeze View Post
    Obviously I'm very new because i thought that if I wanted 9 characters I needed to include '0' so a character array of [8] would give me the 9 characters i need. My friend from class however pointed out that this is not the case so I have since fixed it.
    Other way around. If you have a 9-character filename and you need to store it AND a "zero" at the end, then you need an array[10]!

    Without it, your code *may* (I'm not saying that's the reason it's broke, but it was one of the reasons it didn't work as intended) have been trying to open "sp500.d" (because an array of 8 chars would only hold that much and the end "zero"). Which wouldn't have worked. See how mgracecar used an array of 50 - more than space enough for the filename and a trailing zero.

    If you want code that can open a filename of any size that the user types, you usually have to do that trick. There's no way, using scanf, to know how many characters the user will enter, so you have to have a large "safety" buffer big enough for anything they might type. In general, filenames are less than 256 characters because a lot of operating systems can't handle that amount of characters in a filename or command line anyway.

    - Compiler warnings are like "Bridge Out Ahead" warnings. DON'T just ignore them.
    - A compiler error is something SO stupid that the compiler genuinely can't carry on with its job. A compiler warning is the compiler saying "Well, that's bloody stupid but if you WANT to ignore me..." and carrying on.
    - The best debugging tool in the world is a bunch of printf()'s for everything important around the bits you think might be wrong.

  10. #10
    Registered User
    Join Date
    Mar 2012
    Posts
    4
    Quote Originally Posted by ledow View Post
    In general, filenames are less than 256 characters because a lot of operating systems can't handle that amount of characters in a filename or command line anyway.
    Thats very helpful ledow thanks. I will use that tip from now on. I was just apprehensive at first as I thought the file may not open if i assign too much space in the array, but obviously it doesnt so I will use the 256 buffer size as a general rule from now on

    cheers daeze

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Replies: 3
    Last Post: 07-17-2011, 03:51 AM
  2. File I/O..Reading a file and printing contents
    By eeengenious in forum C Programming
    Replies: 2
    Last Post: 03-14-2011, 05:58 PM
  3. Replies: 13
    Last Post: 05-31-2009, 11:30 AM
  4. Replies: 3
    Last Post: 02-15-2008, 10:54 AM
  5. Reading flat file and generating tagged file
    By AngKar in forum C# Programming
    Replies: 4
    Last Post: 03-24-2006, 08:29 AM