<< Chapter < Page Chapter >> Page >

Write the program opens the file called myfile.txt, and counts the number of characters that it contains by reading all of them one by one. Finally the total amount of bytes is printed out.

#include<stdio.h>int main () {FILE * fp; long n = 0;fp = fopen ("myfile.txt","rb"); if (fp==NULL) printf ("Error opening file");else {while (!feof(fp)) { fgetc (fp);n++; }fclose (fp); printf ("Total number of bytes: %d\n",n);} return 0;}
Got questions? Get instant answers now!

Opens a file called input.txt which has some random text (less than 200 characters), stores each character in an array, then spits them back out into another file called "output.txt" in reverse order:

#include<stdio.h>int main() { char c; /* declare a char variable */char name[200]; /* Initialize array of total200 for characters */ FILE *f_input, *f_output; /* declare FILE pointers */int counter = 0; /* Initialize variable for counter to zero */ f_input = fopen("input.txt", "r");/* open a text file for reading */ if(f_input==NULL) {printf("Error: can't open file.\n"); return 1;} else {while(1) { /* loop continuously */ c = fgetc(f_input); /* fetch the next character */if(c==EOF) { /* if end of file reached, break out of loop */break; }else if (counter<200) { /* else put character into array */ name[counter]= c; counter++; /* increment the counter */} else {break; }} fclose(f_input); /* close input file */f_output = fopen("output.txt", "w"); /* create a text file for writing */if(f_output==NULL) { printf("Error: can't create file.\n");return 1; }else { counter--; /* we went one too step far */while(counter>= 0) { /* loop while counter's above zero */ fputc(name[counter], f_output); /* write character into output file */counter--; /* decrease counter */ }fclose(f_output); /* close output file */ printf("All done!\n");return 0; }} }
Got questions? Get instant answers now!

Reading one character at a time can be a little inefficient, so we can use fgets to read one line at a time. The fgets() function prototype is as follows.

char *fgets(char *str, int num, FILE *fp);

The fgets() function reads characters from the file associated with fp into a string pointed to by str until num-1 characters have been read, a newline character is encountered, or the end of the file is reached. The string is null-terminated and the newline character is retained.

Return value: the function returns str if successful and a null pointer if an error occurs.

You can't use an !=EOF check here, as we're not reading one character at a time (but you can use feof).

Create a file called myfile.txt in Notepad, include 3 lines and put tabs in the last line.

111 222 333 444 555 666777 888 999 #include<stdio.h>int main() {char c[10]; /* declare a char array */FILE *file; /* declare a FILE pointer */ file = fopen("myfile.txt", "r");/* open a text file for reading */ if(file==NULL){ printf("Error: can't open file.\n");/* fclose(file); DON'T PASS A NULL POINTER TO fclose !! */return 1; }else {printf("File opened successfully. Contents:\n\n");while(fgets(c, 10, file)!=NULL) { /* keep looping until NULL pointer... */printf("String: %s", c); /* print the file one line at a time */} printf("\n\nNow closing file...\n");fclose(file); return 0;} }
Got questions? Get instant answers now!

Questions & Answers

what is mutation
Janga Reply
what is a cell
Sifune Reply
how is urine form
Sifune
what is antagonism?
mahase Reply
classification of plants, gymnosperm features.
Linsy Reply
what is the features of gymnosperm
Linsy
how many types of solid did we have
Samuel Reply
what is an ionic bond
Samuel
What is Atoms
Daprince Reply
what is fallopian tube
Merolyn
what is bladder
Merolyn
what's bulbourethral gland
Eduek Reply
urine is formed in the nephron of the renal medulla in the kidney. It starts from filtration, then selective reabsorption and finally secretion
onuoha Reply
State the evolution relation and relevance between endoplasmic reticulum and cytoskeleton as it relates to cell.
Jeremiah
what is heart
Konadu Reply
how is urine formed in human
Konadu
how is urine formed in human
Rahma
what is the diference between a cavity and a canal
Pelagie Reply
what is the causative agent of malaria
Diamond
malaria is caused by an insect called mosquito.
Naomi
Malaria is cause by female anopheles mosquito
Isaac
Malaria is caused by plasmodium Female anopheles mosquitoe is d carrier
Olalekan
a canal is more needed in a root but a cavity is a bad effect
Commander
what are pathogens
Don Reply
In biology, a pathogen (Greek: πάθος pathos "suffering", "passion" and -γενής -genēs "producer of") in the oldest and broadest sense, is anything that can produce disease. A pathogen may also be referred to as an infectious agent, or simply a germ. The term pathogen came into use in the 1880s.[1][2
Zainab
A virus
Commander
Definition of respiration
Muhsin Reply
respiration is the process in which we breath in oxygen and breath out carbon dioxide
Achor
how are lungs work
Commander
where does digestion begins
Achiri Reply
in the mouth
EZEKIEL
what are the functions of follicle stimulating harmones?
Rashima Reply
stimulates the follicle to release the mature ovum into the oviduct
Davonte
what are the functions of Endocrine and pituitary gland
Chinaza
endocrine secrete hormone and regulate body process
Achor
while pituitary gland is an example of endocrine system and it's found in the Brain
Achor
what's biology?
Egbodo Reply
Biology is the study of living organisms, divided into many specialized field that cover their morphology, physiology,anatomy, behaviour,origin and distribution.
Lisah
biology is the study of life.
Alfreda
Biology is the study of how living organisms live and survive in a specific environment
Sifune
Got questions? Join the online conversation and get instant answers!
Jobilize.com Reply

Get Jobilize Job Search Mobile App in your pocket Now!

Get it on Google Play Download on the App Store Now




Source:  OpenStax, Introduction to computer science. OpenStax CNX. Jul 29, 2009 Download for free at http://cnx.org/content/col10776/1.1
Google Play and the Google Play logo are trademarks of Google Inc.

Notification Switch

Would you like to follow the 'Introduction to computer science' conversation and receive update notifications?

Ask