--------------------------------------------------- | Date: 2001-11-24 03:34:34 | | Filename: fileread.c | | Author: detour@metalshell.com | | | | http://www.metalshell.com/ | --------------------------------------------------- /* fileread.c written by detour@metalshell.com * * example of reading a file with fopen() and fgets() * * http://www.metalshell.com/ * */ #include <stdio.h> void stripnl(char *str) { while(strlen(str) && ( (str[strlen(str) - 1] == 13) || ( str[strlen(str) - 1] == 10 ))) { str[strlen(str) - 1] = 0; } } int main() { FILE *infile; char fname[40]; char line[100]; int lcount; /* Read in the filename */ printf("Enter the name of a ascii file: "); fgets(fname, sizeof(fname), stdin); /* We need to get rid of the newline char. */ stripnl(fname); /* Open the file. If NULL is returned there was an error */ if((infile = fopen(fname, "r")) == NULL) { printf("Error Opening File.\n"); exit(1); } while( fgets(line, sizeof(line), infile) != NULL ) { /* Get each line from the infile */ lcount++; /* print the line number and data */ printf("Line %d: %s", lcount, line); } fclose(infile); /* Close the file */ }