Thread: File I/O..Reading a file and printing contents

  1. #1
    Registered User
    Join Date
    Feb 2011
    Posts
    25

    File I/O..Reading a file and printing contents

    Working with file I/O

    Basically, a user inputs a file which they want read. They can enter a sentinel value of "STOP" in which case the program stops.

    The program then opens the file, reads line by line until end of file, and prints each line to the console.

    Little new to file I/O, so wondering if anyone could help me. Here's what I have so far:

    Code:
    #include <stdio.h> 
    #include <string.h>
    
    
    int readSource (char *input); 
    
    int main() {
    
    char input[100]; 
    char sentinel[5] = "STOP" ; 
    
    
    printf("This program will count the number of functions as well as the number of source lines of code in a file.\n"); 
    
    printf("\nEnter name of File:  "); 
    gets(input); 
    
    
    while ((strcmp (input, sentinel) != 0)) {
    
    	readSource(input); 
    
    }
    
    
    getchar();
    
    
    }
    
    
    
    
    int readSource (char *input) {
    
    FILE *fp; 
    fp = fopen("input", "r");
    	if (fp == NULL)
    		{
    		// Error, file not found
    		}
    	else
    		{
    	// Process & close file
    	fclose(fp);
    
    		}
    
    
    }

  2. #2
    Registered User
    Join Date
    Nov 2010
    Location
    Long Beach, CA
    Posts
    5,909
    1. gets is evil and should die. Use fgets on stdin instead.
    2. You said main would return an int, so make it do so. Zero is a fine value for it to return: Cprogramming.com FAQ > main() / void main() / int main() / int main(void) / int main(int argc, char *argv[]).
    3. Look into using fgets for reading the file back and printf, puts, fprintf or fputs to print out the string.

  3. #3
    Registered User
    Join Date
    May 2010
    Location
    Naypyidaw
    Posts
    1,314
    I think the code you posted was given by your tutor? Basically i think you have not done anything at all by yourself.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Reading in a file and printing out a graph from the data
    By levitylek in forum C Programming
    Replies: 3
    Last Post: 10-26-2010, 07:32 PM
  2. Can you help me about tolower() in file
    By nctar in forum C Programming
    Replies: 7
    Last Post: 05-12-2010, 10:04 AM
  3. Reading from file and printing double data
    By hammari in forum C Programming
    Replies: 4
    Last Post: 07-14-2009, 07:02 AM
  4. NEED HELP READING FILE and PRINTING
    By geoffr0 in forum C Programming
    Replies: 4
    Last Post: 04-16-2009, 05:26 PM
  5. Replies: 8
    Last Post: 12-06-2008, 02:43 PM