reading from a file

This is a discussion on reading from a file within the C Programming forums, part of the General Programming Boards category; ive made a simple program to read the number of characters entered from the standard input. i was wondering if ...

  1. #1
    Registered User
    Join Date
    Jun 2007
    Posts
    36

    reading from a file

    ive made a simple program to read the number of characters entered from the standard input.

    i was wondering if someone could help me tweak the program to read from a file instead of from the standard input.

    help plz!

    Code:
    #include <stdio.h>
    #include <string.h>
    
    #define MAX_CHARS 20
    
    int GetStr(char string[], int maxLen);
    
    int main(void)
    {	
    	int stringLength;
    
    	char string[MAX_CHARS + 1] = {'\0'}; 
    
    	printf("Please enter a string:\n");
    
    	stringLength = GetStr(string, MAX_CHARS);
    
    	printf("Length of string is: %d\t",stringLength);
    
    
    	return(0);
    }
    
    /*****************************************************************
    //
    //	GetStr Function definition	
    //
    //	This function reads a series of characters from the user until 
    //	MAX_CHARS is reached.
    //
    /*****************************************************************/
    
    int GetStr(char string[], int maxLen) 
    {
    	int i;
    	for(i=0;i<maxLen;i++)
    		{	
    			string[i]=getchar();
    			if((string[i]=='\n') || (string[i]==EOF))
    				break;
    		}
    
    	string[i]='\0';
    
    	return(i);
    
    }

  2. #2
    Deathray Engineer MacGyver's Avatar
    Join Date
    Mar 2007
    Posts
    3,211
    I would either redirect the program at the command line so stdin would be the file of your choice for input, or else I would rewrite GetStr() to take a FILE * and perform an fgetc() instead of a getchar(). Obviously the fgetc() could act on the file in question. Opening the file and such should be done in main().

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. opening empty file causes access violation
    By trevordunstan in forum C Programming
    Replies: 10
    Last Post: 10-22-2008, 12:19 AM
  2. Formatting the contents of a text file
    By dagorsul in forum C++ Programming
    Replies: 2
    Last Post: 04-29-2008, 01:36 PM
  3. Replies: 3
    Last Post: 03-04-2005, 02:46 PM
  4. Possible circular definition with singleton objects
    By techrolla in forum C++ Programming
    Replies: 3
    Last Post: 12-26-2004, 10:46 AM
  5. System
    By drdroid in forum C++ Programming
    Replies: 3
    Last Post: 06-28-2002, 11:12 PM

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