|
|
| Expert C Programming (ISBN: 0131774298) |
 |
List Price: $39.99
Our Price: $39.99
Used Price: $30.74
Release Date: 14 June, 1994
Manufacturer: Prentice Hall PTR (Paperback)
Sales Rank: 23,761
Author: Peter van der Linden, Peter Van Der Linden
|
More Info
|
|
|
File Reading
|
2001-11-24 03:34:34
|
| |
c
|
|
|
|
|
Category: source:c:files
|
|
Description: Example of reading a file with fopen() and fgets()
|
|
Platform: unix
|
|
Author: detour
|
|
Viewed: 25161
|
|
Rating: 4.2/5 (155 votes)
|
|
|
| If you have any questions about
this piece of code or still need help, try posting your question on the forum. |
/* 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 */
}
|
|
|