Download presentation
Presentation is loading. Please wait.
1
CSE1320 Files in C Dr. Sajib Datta
2
Files in C A file is viewed as a stream of bytes by a C program.
When a C program is executed, three files are automatically opened: Standard input, input from the keyboard Standard output, output to the monitor screen Standard error, be associated with the terminal output They are referenced with the identifiers stdin, stdout and stderr, respectively, having the FILE * type.
3
Standard files – Standard I/O
standard input (stdin) – the normal input device for your system, e.g., keyboard scanf(), getchar(), gets() standard output (stdout) – the normal output device for your system, e.g., display screen printf(), putchar(), puts()
4
#include <stdio.h>
int main(void) { char mych[2]; scanf("%c", &mych[0]); mych[1] = getchar(); printf("The char arry has %c and %c.\n", mych[0], mych[1]); return 0; }
5
Files Operation in C Program
When working with files in C, declare a FILE * variable – file identifier FILE * fp; scanf(), getchar(), gets() Then building a connection for the identifier with a file using fopen( )
6
Associate the variable with a file
FILE * fopen (char * filename, char * mode ); Specify the file path and the mode If successful, fopen returns a file pointer; otherwise, NULL is returned: a file we wish to read may not exist a file we wish to write to may be in use by another program
7
fclose() Use fclose() when you are finished working with the files
int fclose ( FILE * stream ); Return Value If the stream is successfully closed, a zero value is returned. On failure, EOF is returned.
8
#include <stdio.h>
#include <stdlib.h> int main(void) { FILE *fp; if((fp = fopen("info", "r")) == NULL) printf("Input file could not be opened.\n"); exit(1); } if(fclose(fp) == EOF) printf("File couldn't be closed.\n"); return 0;
9
exit() exit() function causes the program to terminate, closing any open files. Passing a value of zero for programs that terminate normally, and a non-zero value for abnormal termination Different from return, for a recursive program, return will pass flow control to the previous level of recursion until the original level is reached. exit() still terminates the program.
10
Character input and output
To read in or write out text by character, use getc( ) and putc( ) char getc ( FILE * stream ); returns the char, if successful; otherwise, EOF (the end of the file) ch = getc(stdin) is equivalent to ch = getchar() Before use getc(), a call to fopen() should be made to open a file for reading. char putc ( char character, FILE * stream ); If successful, the character is returned; otherwise, EOF is returned putc(ch,stdout) is equivalent to putchar(ch), where ch is a character, for example, char ch = ‘a’; Before use putc(), the file must have been opened for writing. Both in stdio.h
11
getc() and putc() #include <stdio.h> int main(void) { char mych; mych = getc(stdin);// mych = getchar(); putc(mych, stdout);// putchar(mych); return 0; }
12
The End of File EOF EOF indicates the end of the file
To check for the end of the file, two approaches use (ch = getc(fp)) == EOF int feof ( FILE * stream ); A non-zero value is returned in the case that the End-of-File indicator associated with the stream is set. Otherwise, a zero value is returned. Included in stdio.h You can learn more about EOF from
13
A sample program to read input from a file and store the output to an another file.
#include <stdio.h> #include <stdlib.h> // For exit() function int main() { char c[1000]; FILE *fptr; if ((fptr = fopen(“program.txt”, “r”)) == NULL) printf("Error opening file!"); exit(1); } // reads text until newline fscanf(fptr,"%[^\n]", c); printf("Data from the file:\n%s", c); fclose(fptr); return 0;
14
> cat program.txt Welcome to Intermediate Programming Course We are learning I/O and files. Have fun coding! Output > gcc file.c -o file > ./file >> output.txt > cat output.txt Data from the file:
15
A sample C program to create a file and write data into file.
#include <stdio.h> #include <stdlib.h> #define DATA_SIZE 1000 int main() { /* Variable to store user content */ char data[DATA_SIZE]; /* File pointer to hold reference to our file */ FILE * fptr; /* Open file in w (write) mode.*/ fptr = fopen("file1.txt", "w"); if(fptr == NULL) /* File not created hence exit */ printf("Unable to create file.\n"); exit(EXIT_FAILURE); }
16
/* Input contents from user to store in file */
printf("Enter contents to store in file : \n"); fgets(data, DATA_SIZE, stdin); /* Write data to file */ fputs(data, fptr); /* Close file to save file data */ fclose(fptr); printf("File created and saved successfully. \n"); return 0; }
17
Output > gcc sample.c -o sample >./sample Enter contents to store in file : Hello World! This is a sample text file File created and saved successfully. > vi file1.txt This is a sample text file
18
#include <stdio.h>
#include <stdlib.h> int main(void) { char ch; FILE * fp; fp = fopen("myfiles.txt","r"); ch = getc(fp); while(ch != EOF) putchar(ch); } return 0;
19
Find the number of a specific character in a file
#include <stdio.h> #include <stdlib.h> int main(void) { char mych,ch; int counter = 0; FILE * fp = fopen("myfiles.txt", "r"); if (fp == NULL) printf("Can't open the file.\n"); exit(1); } printf("Please input a character:"); scanf("%c", &mych); ch = getc(fp); while(ch != EOF) if (ch == mych) counter++; printf("Totally, there are %d characters of '%c'.\n", counter, mych); fclose(fp); return 0;
20
String input and output
char * fgets ( char * str, int num, FILE * stream ); Reads characters from stream and stores them as a C string into str until (num-1) characters have been read or either newline or the End-of-File (EOF) is reached, whichever comes first. A newline character is a valid character! Different from gets() function. A null character is automatically appended to str. Return data On success, the function returns str. If the end-of-file is encountered while attempting to read a character, the eof indicator is set (feof). If this happens before any characters could be read, the pointer returned is a null pointer (and the contents of str remain unchanged). If a read error occurs, the error indicator (ferror) is set and a null pointer is also returned (but the contents pointed by str may have changed).
21
Count characters on each line
#include <stdio.h> #include <stdlib.h> #include <string.h> int main(void) { char chbuffer[100];// assume the number of characters in each line < 100 int counterline = 0, counterch; FILE * fp = fopen("myfiles.txt", "r"); if (fp == NULL) printf("Can't open the file.\n"); exit(1); } while (fgets(chbuffer, 100, fp) != NULL) counterline++; counterch = strlen(chbuffer); printf("Line %d has %d characters.\n", counterline, counterch); fclose(fp); return 0; Soft assignment: How to code the program to remove the assumption!!!!
Similar presentations
© 2024 SlidePlayer.com. Inc.
All rights reserved.