sometimes a cigar is just a cigar
Header image

How to Read File with C

Posted by ALonon in C++

I wrote c code to read from a file char by char. Finally, it counts char number and print it.
How to read file with C
1. Get file name to open.
2. Open file to read.
3. Get a char.
4. Print char.
5. Print total char in the file.

#include 
void main () {
	char getname[10],c=" ";
	int i=0,totalchar=0;
	FILE *mytxt;
	while(i == 0) {
		printf("Please write file name(max:10 char):\n");
		gets(getname);
		mytxt = fopen(getname,"r");
		if(mytxt == NULL)
			printf("File can not found\n");
		else {
			i=1;
			while(!feof(mytxt)) {
				c = getc(mytxt);
				if(c != EOF) {
					printf("%c",c);
					totalchar++;
				}
			}
		}
	}
    fclose(mytxt);
    printf("In %s file , there are %d chars.",getname,--totalchar);
    return 0;
}

You can follow any responses to this entry through the RSS 2.0 You can leave a response, or trackback.

Leave a Reply

Your email address will not be published. Required fields are marked *

*

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>