Thread: Opening File in C

  1. #1
    Registered User
    Join Date
    Aug 2011
    Posts
    8

    Opening File in C

    Hey Everyone.
    I am slightly stuck in writing this code and would appreciate any help.
    This is only the start of the actual the program. The program is menu driven, the first menu gives the user 2 options to either open a file or exit the program. If option 1, open a file is entered then the user needs to input the file name. If correct its meant to display another menu but if its incorrect then its meant to display that the file cannot be found and then display the first menu again.
    This is what I have so far, Im just not sure how to go back to the first menu after an incorrect file name is inputted and also how to go to the next menu if it is correct.

    Code:
    #include <stdio.h>
    
    int main()
    {
    int d;
    
    
    printf("\n\n\t\tMenu:\n");
    printf("\n\n\t\t[1] Open a File (Supported .grc)\n");
    printf("\t\t[2] Exit\n");
    printf("\n\n\t\tPlease Select and Option [1 or 2]:");
    scanf("%d", &d);
    
    switch(d)
    {
    case 1:
    {
    
    FILE *fp;
    char fname[100]="";
    printf("\n\tEnter File Name:");
    scanf("%s",&fname);
    		fp=fopen(fname,"rb");
    		if(fp==NULL)
    {
    printf("\n%s\" File Not Found!",fname);
    getch();
    
    }
    {
    case 2:
    exit(0);
    }
    return 0;
    }
    }}
    Any help would be great.
    Thanks

  2. #2
    Registered User
    Join Date
    May 2011
    Location
    Around 8.3 light-minutes from the Sun
    Posts
    1,949
    You need to start setting up functions. Read the function tutorial and apply that to your problem. Additionally, the loop tutorial will help you out as well.

    Plus read How to define Main() FAQ and your code could use indentation. You can read about how to indent properly here.

    Also, single letter variable names that are not loop iterators are wrong. Don't do that. Additionally, getch() is compiler specific. May I suggest something standard compliant such as getchar() instead.
    Quote Originally Posted by anduril462 View Post
    Now, please, for the love of all things good and holy, think about what you're doing! Don't just run around willy-nilly, coding like a drunk two-year-old....
    Quote Originally Posted by quzah View Post
    ..... Just don't be surprised when I say you aren't using standard C anymore, and as such,are off in your own little universe that I will completely disregard.
    Warning: Some or all of my posted code may be non-standard and as such should not be used and in no case looked at.

  3. #3
    Banned
    Join Date
    Aug 2010
    Location
    Ontario Canada
    Posts
    9,547
    Ok... this is your one and only freebie...

    Code:
    #include <stdio.h>
    #include <stdlib.h>
    
    int main (void)
      { FILE *infile = NULL;
        char fname[256] = {0};
    
        do
          { printf("Enter a filename (blank to exit) : ";
             if (! fgets(fname,256,stdin) )
               { printf(" Exiting\n\n");
                  exit (0); }   
             
            infile = fopen(fname,"rb"); }
        while (!infile);
    
        // rest of program here
    
       return 0; }
    1) Menus are fine when you have more than 2 choices to deal with. Making your operators enter constant strings of unnecessary menu choices generally does nothing but try their patience.

    2) You need to sit down and PLAN your programs first. Writing code is the LAST step in developing a working program. First you need to understand the problem you are attempting to solve, then you need to plan out your solution... all done with paper and pencil. It is a serious mistake to think that programmers are handed and assignment and then just start typing code... that's Hollywood... it makes good drama but it makes lousy software.

  4. #4
    Registered User
    Join Date
    Aug 2011
    Posts
    8
    Ok I've got most of the code written now im just down to the last part...I obviously don't want or expect any code written for me I just need a little push into the right direction. After I have opened a file which I have done I need to read the sequence of bytes from the binary file and then decompose each byte into 2 gray coded 4 bit numbers..then it goes on to decode them into hexadecimal values and then display them. I have these 2 lines of code to include into this function but I'm a bit stuck on how to read the file and change it into the 2 gray coded bit numbers.

    Code:
    /* define the decoding table */
    unsigned char decodingTable[16] = { 0, 1, 3, 2, 7, 6, 4, 5, 0xF, 0xE, 0xC, 0xD, 8, 9, 0xB, 0xA };
    
    
    /* get a decoded value from the position equal its Gray code */
    hexValue = decodingTable[ grayCode ];
    Any help would be great.

    Thanks

  5. #5
    Registered User
    Join Date
    Aug 2011
    Posts
    8
    This is the program so far. I have to have the two menu's btw.

    Code:
    #include <stdio.h>
    #include <stdlib.h>
    
    
    void load_menu2(void);
    void OpenFile();
    void decodeTable();
    
    int main()
    {
    	int choice;
    	
    	
    	do
    	{
    		printf("\n\n\t\tMenu:\n");
    		printf("\n\n\t\t[1] Open a File (Supported .grc)\n");
    		printf("\t\t[2] Exit\n");
    		printf("\n\n\t\tPlease Select and Option [1 or 2]: ");
    		scanf("%d", &choice);
    		
    		switch(choice)
    		{	
    			case 1:OpenFile();
    				break;
    			case 2: printf("\nProgram Terminated!\n");
    				exit(0);
    				break;
    			default: printf("\nInvalid Choice!\n");
    				break;
    	    }	 
    	 }
    	while (choice !=2);
    		
    
    
    return 0;
    }
    
    void OpenFile()
    {
    	FILE *fp;
    	char fname[100]="";
    	printf("\n\tEnter File Name:");
    	scanf("%s",&fname);
    			fp=fopen(fname,"rb");
    			if(fp==NULL)
    		{
    			printf("\n%s\" File Not Found!",fname);
    			getchar();
    		}
    			else
    				load_menu2();
    				
    }
    
    void load_menu2(void)
    {
                   int choice2;
    	
    	do
    	{
    		printf("\n\n\t\tMenu:\n");
    		printf("\n\n\t\t[1] Decode the Sequence\n");
    		printf("\t\t[2] Exit\n");
    		printf("\n\n\t\tPlease Select and Option [1 or 2]: ");
    		scanf("%d", &choice2);
    		
    		switch(choice2)
    		{	
    			case 1:
    					/*decodetable();*/
    										printf("works");
    				break;
    			case 2: printf("\nProgram Terminated!\n");
    				exit(0);
    				break;
    			default: printf("\nInvalid Choice!\n");
    				break;
    		}
    	}	 while (choice2 !=2);
    }

  6. #6
    and the Hat of Guessing tabstop's Avatar
    Join Date
    Nov 2007
    Posts
    14,336
    Quote Originally Posted by bodyboarder91 View Post
    Ok I've got most of the code written now im just down to the last part...I obviously don't want or expect any code written for me I just need a little push into the right direction. After I have opened a file which I have done I need to read the sequence of bytes from the binary file and then decompose each byte into 2 gray coded 4 bit numbers..then it goes on to decode them into hexadecimal values and then display them. I have these 2 lines of code to include into this function but I'm a bit stuck on how to read the file and change it into the 2 gray coded bit numbers.

    Code:
    /* define the decoding table */
    unsigned char decodingTable[16] = { 0, 1, 3, 2, 7, 6, 4, 5, 0xF, 0xE, 0xC, 0xD, 8, 9, 0xB, 0xA };
    
    
    /* get a decoded value from the position equal its Gray code */
    hexValue = decodingTable[ grayCode ];
    Any help would be great.

    Thanks
    So you've written down how to do it:
    • Read a byte
    • Split it into top four bits and bottom four bits (you'll need bitwise operators to do this, natch)
    • Decode the top bits
    • Display it
    • Decode the bottom bits
    • Display it

    Work out how to do each step. You appear to have the "Decode" step down.

  7. #7
    Registered User
    Join Date
    Aug 2011
    Posts
    8
    Ok im struggling with the reading part. In the other parts of the program I open the file and then go to another menu and when I choose option one its meant to display the values in hexadecimal.
    Can I put the read part in the same function that displays it and not in the function that opens the file?

    So far I have this I know its wrong but any guidance would be appreciated.

    Code:
    void decodeTable()
    {
    	FILE *fp;
    	unsigned char hexValue;
    	unsigned char decodingTable[16] = { 0, 1, 3, 2, 7, 6, 4, 5, 0xF, 0xE, 0xC, 0xD, 8, 9, 0xB, 0xA };
    	
      	read(fp, &hexValue, sizeof(hexValue));
    	hexValue = decodingTable[16];
    		
        printf("<%X>\n", hexValue);
    
    
    	}
    Last edited by bodyboarder91; 08-18-2011 at 09:35 PM.

  8. #8
    Registered User
    Join Date
    May 2011
    Location
    Around 8.3 light-minutes from the Sun
    Posts
    1,949
    Yes you could, you would just have to pass your file pointer to your decode function. Where do you open the file? Also, what are you trying to do with this line? (Keep in mind arrays start at 0)
    Code:
    hexValue = decodingTable[16];
    Last edited by AndrewHunter; 08-18-2011 at 09:51 PM.
    Quote Originally Posted by anduril462 View Post
    Now, please, for the love of all things good and holy, think about what you're doing! Don't just run around willy-nilly, coding like a drunk two-year-old....
    Quote Originally Posted by quzah View Post
    ..... Just don't be surprised when I say you aren't using standard C anymore, and as such,are off in your own little universe that I will completely disregard.
    Warning: Some or all of my posted code may be non-standard and as such should not be used and in no case looked at.

  9. #9
    Registered User
    Join Date
    Aug 2011
    Posts
    8
    So by adding this to the decodeTable function it will pass the file pointer to it?

    Code:
    FILE *fp;
    The file opens here.
    Code:
    void OpenFile()
    {
    	FILE *fp;
    	char fname[100]="";
    	printf("\n\tEnter File Name:");
    	scanf("%s",&fname);
    			fp=fopen(fname,"rb");
    			if(fp==NULL)
    		{
    			printf("\n%s\" File Not Found!",fname);
    			getchar();
    		}
    			else
    				load_menu2();
    				
    }
    ah yes well that was a mistake think its meant to look more like this
    Code:
     hexValue = decodingTable[graycode];
    Is the read line
    Code:
    read(fp, &hexValue, sizeof(hexValue));
    correct? I think im a little ahead of myself at the moment though since I still havent figured out how to split each byte into the 2 4 bit numbers.

  10. #10
    Registered User
    Join Date
    May 2011
    Location
    Around 8.3 light-minutes from the Sun
    Posts
    1,949
    You can read up on fread() here

    And your answer is no, you will have to pass the file pointer as an argument to your function. Read about functions with Lesson 4 Functions.

    Additionally, you are going to want to read up on bit manipulation in order to actually accomplish your task.
    Quote Originally Posted by anduril462 View Post
    Now, please, for the love of all things good and holy, think about what you're doing! Don't just run around willy-nilly, coding like a drunk two-year-old....
    Quote Originally Posted by quzah View Post
    ..... Just don't be surprised when I say you aren't using standard C anymore, and as such,are off in your own little universe that I will completely disregard.
    Warning: Some or all of my posted code may be non-standard and as such should not be used and in no case looked at.

  11. #11
    Registered User
    Join Date
    Aug 2011
    Posts
    8
    the fread() line is meant to look something like this according to the page you linked..

    Code:
    size_t fread ( void * ptr, size_t size, size_t count, FILE * stream );
    I got confused slightly when looking at this but I gave it a go and is this what mine should look like?

    Code:
     fread(FILE *fp, 1, 1size, fp)

    This is the new function prototype now as well

    Code:
    unsigned char decode(unsigned char hexValue, FILE *fp);
    changed the name of the function to just decode.
    Last edited by bodyboarder91; 08-19-2011 at 04:34 AM.

  12. #12
    Banned
    Join Date
    Aug 2010
    Location
    Ontario Canada
    Posts
    9,547
    You need to grab your C textbook (or a good online tutorial) and go through it page by page... Start on page 1, READ the text, type up the examples, do the exercises, mess with the code, until you understand it, then move on to the next page... A good study level review will help you enormously...

  13. #13
    Registered User
    Join Date
    May 2011
    Location
    Around 8.3 light-minutes from the Sun
    Posts
    1,949
    Ok, you seem to be missing some pointes here. The easiest way to do this is to:

    1. open the file
    2. load the entire file into memory (an array you made with malloc)
    3. close the file
    4. move on to your decoding sequence with your array.

    For step 2, refer to the link I posted for you; it shows you how to do this.
    Quote Originally Posted by anduril462 View Post
    Now, please, for the love of all things good and holy, think about what you're doing! Don't just run around willy-nilly, coding like a drunk two-year-old....
    Quote Originally Posted by quzah View Post
    ..... Just don't be surprised when I say you aren't using standard C anymore, and as such,are off in your own little universe that I will completely disregard.
    Warning: Some or all of my posted code may be non-standard and as such should not be used and in no case looked at.

  14. #14
    Registered User
    Join Date
    Aug 2011
    Posts
    8
    Ok from what I have read it sounds like its easier to open and read the file in the one function and then go to another function to decode the file.

    This is now the openFile function

    Code:
    void OpenFile(void)
    {
    	FILE *fp;
    	long lSize;
            char * buffer;
            size_t result;
    	char fname[100]="";
    	
    	printf("\n\tEnter File Name: ");
    	scanf("%s",&fname);
    			fp=fopen(fname,"rb");
    			if(fp==NULL)
    		{
    			printf("\n%s\" File Not Found!",fname);
    			getchar();
    		}
    			else
    	{	 	 
    		fseek (fp , 0 , SEEK_END);
    		lSize = ftell (fp);
    		rewind (fp);
    			
    			
    		buffer = (char*) malloc (sizeof(char)*lSize);
    			
    		result = fread (buffer,1,lSize,fp);
          	   
    		
    		fclose (fp);
                    free (buffer);	     
    		
    		load_menu2();
    	}
    				
    }
    Would that be correct? So the file is now loaded into an array? So then when I call the decode function after I choose option 1 in the load_menu2, that function will have to split each 8 bit number in the array into 2 4 bit numbers and then I point the value of each 4 bit number to my array decodingTable[]?

    Full program again.

    Code:
    #include <stdio.h>
    #include <stdlib.h>
    
    
    unsigned char decodingTable[] = { 0, 1, 3, 2, 7, 6, 4, 5, 0xF, 0xE, 0xC, 0xD, 8, 9, 0xB, 0xA };
    
    void load_menu2(void);
    void OpenFile(void);
    unsigned char decode();
    
    int main()
    {
    	int choice;
    	
    	
    	do
    	{
    		printf("\n\n\t\tMenu:\n");
    		printf("\n\n\t\t[1] Open a File (Supported .grc)\n");
    		printf("\t\t[2] Exit\n");
    		printf("\n\n\t\tPlease Select and Option [1 or 2]: ");
    		scanf("%d", &choice);
    		
    		switch(choice)
    		{	
    			case 1:OpenFile();
    				break;
    			case 2: printf("\nProgram Terminated!\n");
    				exit(0);
    				break;
    			default: printf("\nInvalid Choice!\n");
    				break;
    	    }	 
    	 }
    	while (choice !=2);
    		
    
    
    return 0;
    }
    
    void OpenFile(void)
    {
    	FILE *fp;
    	long lSize;
        char * buffer;
        size_t result;
    	char fname[100]="";
    	
    	printf("\n\tEnter File Name: ");
    	scanf("%s",&fname);
    			fp=fopen(fname,"rb");
    			if(fp==NULL)
    		{
    			printf("\n%s\" File Not Found!",fname);
    			getchar();
    		}
    			else
    	{	 	 
    		fseek (fp , 0 , SEEK_END);
    		lSize = ftell (fp);
    		rewind (fp);
    			
    			
    		buffer = (char*) malloc (sizeof(char)*lSize);
    			
    		result = fread (buffer,1,lSize,fp);
          	   
    		
    		fclose (fp);
            free (buffer);	     
    		
    		load_menu2();
    				}
    				
    }
    
    void load_menu2()
    {
    
    	int choice2;
    	
    	do
    	{
    		printf("\n\n\t\tMenu:\n");
    		printf("\n\n\t\t[1] Decode the Sequence\n");
    		printf("\t\t[2] Exit\n");
    		printf("\n\n\t\tPlease Select and Option [1 or 2]: ");
    		scanf("%d", &choice2);
    		
    		switch(choice2)
    		{	
    			case 1: decode();
    				break;
    			case 2: printf("\nProgram Terminated!\n");
    				exit(0);
    				break;
    			default: printf("\nInvalid Choice!\n");
    				break;
    		}
    	}	 while (choice2 !=2);
    }
    
    
    unsigned char decode()
    {
    printf("works");
    
    	}

  15. #15
    Registered User
    Join Date
    May 2011
    Location
    Around 8.3 light-minutes from the Sun
    Posts
    1,949
    You really need to read the lesson on functions. A couple of notes:
    1. Do not cast the return of malloc. Read FAQ-Casting Malloc
    2. You free your buffer before you use it. That data is gone.
    3. Your buffer is local to your function. Once you leave that function the buffer goes out of scope and you can't access it anymore (if you didn't free it).

    So, what to do:

    1. Place your buffer in main. (char* buffer=NULL)
    2. Pass your buffer to your open file function
    3. Open your file
    4. alloc space for your buffer. Check to ensure malloc worked (if(!buffer) exit(1))
    5. Fill your buffer with fread.
    6. close the file
    7. Call your decode function and pass your buffer to it.
    Quote Originally Posted by anduril462 View Post
    Now, please, for the love of all things good and holy, think about what you're doing! Don't just run around willy-nilly, coding like a drunk two-year-old....
    Quote Originally Posted by quzah View Post
    ..... Just don't be surprised when I say you aren't using standard C anymore, and as such,are off in your own little universe that I will completely disregard.
    Warning: Some or all of my posted code may be non-standard and as such should not be used and in no case looked at.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. File opening
    By cnewbie1 in forum C Programming
    Replies: 2
    Last Post: 12-28-2010, 08:16 AM
  2. About file opening
    By kira_coder in forum Windows Programming
    Replies: 5
    Last Post: 03-14-2010, 11:15 PM
  3. File opening
    By al_engler in forum C Programming
    Replies: 3
    Last Post: 12-27-2006, 05:46 PM
  4. file opening?
    By ssjnamek in forum C Programming
    Replies: 24
    Last Post: 03-01-2006, 08:15 AM
  5. opening a file in dos
    By makveli in forum C++ Programming
    Replies: 6
    Last Post: 11-12-2003, 04:42 PM