0% found this document useful (0 votes)
18 views24 pages

CSE109 Week10

Uploaded by

chakmanirjha
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
18 views24 pages

CSE109 Week10

Uploaded by

chakmanirjha
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 24

Files

Lecture: 21-22
Reference Book: Teach yourself C (3rd Ed.)
Chapter/Section: -

Samin Rahman Khan


Lecturer (part-time), CSE, BUET
Lecturer, IICT, BUET
Stream
• Abstraction between hardware and programmer
• Actual device providing I/O is file
• File can refer to disk file, screen, keyboard, memory, port,
tape file or others
• Stream is a logical interface to a file
• When a C program started operating system opens three files
and associated streams
• Standard input: stdin
• Standard output: stdout
• Standard error: stderr
• Declared in stdio.h
Types of Streams (Files)
• Text
• Some character translations may take place
• There may not be one-to-one correspondence between what is
sent to stream and what is written to the file

• Binary
• No character translation will occur
• There is one-to-one correspondence
Open a File
FILE *fopen (char *filename, char
*mode);
• In <stdio.h>
• Filename
Mode Strings
• Path of the file
• “r”, “w”, “a”, “
• Mode
• r+”, “w+”,”a+”
• Text/binary (b)
• Read (r)/write (w)/append (a) • “rb”,”wb”, “ab”,

• Returns a pointer to the opened • “rb+”,”wb+”,”ab+”


file
• If fails returns NULL
Mode
• Read mode ("r")
• if file is unavailable error
• Write mode (“w")
• if file is unavailable created
• If file exists truncated
• Append mode (“a")
• if file is unavailable created

Image ref: https://i.stack.imgur.com/AJW8x.png


Close a File
int fclose (FILE *fp);

• In order to improve efficiency most file system write data to


disk one sector at a time
• fclose flushes the buffer
Sample Code
#include<stdio.h>
#include<stdlib.h>
The file must be in the
int main() same folder of the .c
{ file. Else need to
FILE * fp; specify the path
//fp = fopen("f1.txt", "r"); // to open file in read mode
fp = fopen("f1.txt", "w"); // to open file in write mode
if (fp == NULL)
{
printf("File doesn't exists!\n");
exit(1);
}
printf("File successfully opened\n");
//Write to file
fclose(fp);
return 0;
}
Read/Write a Character
int fgetc (FILE *fp);
- Normal: reads the next byte from the file and returns it as integer
- If error/file reading ends: returns EOF
• fgetc(stdin) same as getchar()

int fputc (int ch, FILE *fp);


- Normal: writes the content of ch to the file and returns it as integer
- If error/file reading ends: returns EOF
- fputc(‘a’, stdout) same as putchar(‘a’)
Use of fputc and fgetc #include<stdio.h>
int main(){
FILE *fp;
#include<stdio.h>
char ch;
int main(){
int temp;
FILE *fp;
char ch; fp = fopen("f2.txt", "r");
if(fp==NULL)
open
int temp;
{
fp=fopen("f2.txt","w");
if(fp==NULL)
open printf("Error during reading file\n");
return 1;
{
}
printf("Error in creating file\n");
printf("File successfully opened\n");
return 1;
while(1){
}
ch = fgetc(fp); read
printf("File successfully opened\n"); if ( ch != EOF ) printf("%c",ch);
while(1) else break;
{ write }
temp=scanf("%c",&ch); // better way
if (temp==EOF) break; /*while( ( ch = fgetc(fp) ) != EOF ){
fputc(ch,fp); printf("%c", ch);
} }*/
printf("File successfully read\n");
printf("File successfully written\n");
fclose(fp); close
fclose(fp); close
return 0;
return 0;
}
}
EOF
• To denote end of file
• An integer defined in <stdio.h>
• Value is different than any character values, normally is it -1
• Given by Ctrl+z (if you want to manually give it)
• Used in file
• Used when input taken in continuous loop
End of File
int feof (FILE *fp);
• Returns non zero if fp reached end of file
• Returns 0 otherwise

int ferror (FILE *fp);


• Returns non zero if fp faced any error during
read/write
• Returns 0 otherwise
Writing and reading strings and others

int fputs (char *str, FILE *fp);


- Writes the content of str to the file until a null character is found
- The null that terminates str is not written
- Returns EOF if an error occurs and a non-negative value is successful

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


• Reads characters from the file to str
• Until
• num-1 characters have been read
• End of file reached
• Newline reached
• str is null terminated
• Returns str if successful, NULL otherwise
Use of fputs and fgets
#include<stdio.h> #include<stdio.h>
#include<string.h> #include<string.h>
#include<stdlib.h> #include<stdlib.h>
int main(){
FILE * fp; int main(){
char str[80]; FILE * fp;
int i, N = 5; char str[80];
fp = fopen("f3", "w");
if (fp == NULL) open fp = fopen("f3.txt", "r"); open
{ if (fp == NULL)
printf("File doesn't exists!\n"); {
exit(1); printf("File doesn't exists!\n");
} exit(1);
}

printf("Enter %d lines to save in a file:\n", printf("Your lines:\n");


N); while(!feof(fp))
{ read
for ( i = 0; i < N; i++) fgets(str, 80, fp); // to read a string
{ write from a file
gets(str); if (!feof(fp))
strcat(str, "\n"); // need to append the printf("%s", str);
'\n’ because fgets use it as terminator }
fputs(str, fp); // to write a string in a
file fclose(fp);
} close
return 0;
fclose(fp); }
close
}
Writing and reading strings and
others
int fprintf (FILE *fp, format specifier(s), variable(s));
• Just like printf.
• Return
• ON SUCCESS: the number of bytes output
• ON FAILURE: returns EOF
int fscanf (FILE *fp, format specifier(s), address(es));
• Just like scanf.
• Return
• ON SUCCESS: Number of scanned inputs.
• ON FAILURE: fscanf returns EOF
Use of fprintf and fscanf
#include<stdio.h> #include<stdio.h>
#include<string.h> #include<string.h>
#include<stdlib.h> #include<stdlib.h>

int main() int main()


{ {
FILE * fp; FILE * fp;
char str[80]; char str[80];
int i; int i;
float f; float f;

fp = fopen("f4.txt", "w"); fp = fopen("f4.txt", "r");


if (fp == NULL) if (fp == NULL)
{ {
printf("File doesn't exists!\n"); printf("File doesn't exists!\n");
exit(1); exit(1);
} }

// to write in a file, similar as printf while (!feof(fp))


fprintf(fp, "%f %s %d ", 100.5, "hello", 20); {
fprintf(fp, "%f %s %d ", 345.5, "world", 10); // to read from a file, similar as scanf
fscanf(fp, "%f %s %d ", &f, str, &i);
fclose(fp); printf("%f %s %d\n", f, str, i);
}
}
fclose(fp);
return 0;
}
Writing and reading in binary file
size_t fread (void *buffer, size_t size, size_t num, FILE *fp);
Size_t is a type able to represent the size of any object in bytes. It is guaranteed to be big enough
to contain the size of the biggest object the host system can handle. For simplicity, in general
setting, you can consider it as equivalent to unsigned long int (though may depend on operating
system properties)
• buffer: where the output of fread will be stored
• size: size of the object to be read
• num: number of the objects to be read
• fp: the stream of the source file from where we want to read

size_t fwrite (void *buffer, size_t size, size_t num, FILE *fp);
• buffer: address of the memory which is the start address to write
• size: size of the object to be written
• num: number of the objects to be written
• fp: the stream of the destination file where we want to write
Use of fwrite and fread
#include<stdio.h> #include<stdio.h>
struct student struct student
{ {
int id; int id;
double cgpa; double cgpa;
}; };
int main(){ int main(){
int n,i, max; int n,i, max;
struct student s[10]; struct student s[10];
FILE *fp; FILE *fp;

fp = fopen("f5","wb"); fp=fopen("f5","rb");
if(fp==NULL) if(fp==NULL)
return 1; return 1;

scanf("%d",&n); scanf("%d",&n);
for(i=0;i<n;i++) for(i=0;i<n;i++)
{ {
scanf("%d %lf",&s[i].id, &s[i].cgpa); fread(&s[i],sizeof(s[i]),1,fp);
} }
for(i=0;i<n;i++) //Reading all at once without any loop
{ //fread(&s[0],sizeof(s[0]),n,fp);
fwrite(&s[i],sizeof(s[i]),1,fp);
} for(i=0;i<n;i++)
//Writing all at once without any loop {
//fwrite(&s[0],sizeof(s[0]),n,fp); printf("%d %lf\n",s[i].id,s[i].cgpa);
} }
fclose(fp);
return 0;
}
freopen
FILE *freopen(const char *filename, const char *mode, FILE
*stream)
• associates a new filename with the given open stream and at the
same time closes the old file in the stream.

For example,
freopen(“input.txt","r",stdin);
stdin was the default stream originally associated with console
(console is considered as a file). After the freopen function call,
stdin has been used to open a new stream to file “input.txt”.
So, scanf will read its input from “data_input.txt”.
Use of freopen
#include<stdio.h>

int main()
{
int i, j, n, arr[10];

freopen("input.txt","r",stdin);

freopen("output.txt","w",stdout
);

scanf("%d",&n);
for(i=0;i<n;i++)
scanf("%d",&arr[i]);

for(i=0;i<n;i++)
printf("%d ",arr[i]);
return 0;
}
File Operations
• File handle : FILE *
• Open a file : fopen
• Input/Output
• Character IO : fgetc, fputc
• String IO : fgets, fputs
• Formatted IO : fscanf, fprintf
• Raw IO : fread, fwrite
• Close a file : fclose
• Other operations :
• freopen, fseek, ftell
Sample Exercise
• Suppose, you are given two input files named “input1.txt” and “input2.txt”.
In both of the files, a single line contains an integer number. Both the files
contain same number of integers. There will be an output file named
“output.txt”. You have to take the 1st integer of input file 1 and the 1st integer
of input file 2, and output their summation in the 1 st line of the output file.
Then take the 2nd integers from both the inputs files and output their
summation in the second line of output file, and so on up to the end of the
input files. Write the full C code for this.
1st input file 2nd input file Correspondin
sample data sample data g output file
sample data
2 100 102
4 4 8
-2 98 96
4 -100 -96
8 -8 0
Solution
#include<stdio.h> while(fscanf(fp1,"%d",&i)!=EOF &&
fscanf(fp2,"%d",&j)!=EOF)
int main(int argc,char *argv[]) {
{ k=i+j;
FILE *fp1, *fp2, *fp3; fprintf(fp3,"%d\n",k);
int i,j,k; }
fp1 =
fopen("data_input1.txt","r"); fclose(fp1);
if(fp1==NULL) fclose(fp2);
{ fclose(fp3);
printf("Cannot open file\n");
exit(1); return 0;
} }
fp2 =
fopen("data_input2.txt","r");
if(fp2==NULL)
{
printf("Cannot open file\n");
exit(1);
}
fp3 =
fopen("data_output.txt","w");
if(fp3==NULL)
{
printf("Cannot open file\n");
exit(1);
}
Acknowledgement
This slide has been prepared by taking help from numerous resources. The notable contributors
are listed below.
1. The slides have been compiled and curated by Khaled Mahmud Shahriar, Assistant
Professor, CSE, BUET for CSE287 offered to the Department of MME.
2. Content and organization of many pages have been taken from the lecture slides and codes
of the course CSE110 offered to the Department of EEE that were -
i. primarily created by Johra Muhammad Moosa, Assistant Professor (on leave), CSE,
BUET and
ii. later modified by Madhusudan Basak, Assistant Professor, CSE, BUET
3. Most of the wonderful coding examples have been taken from the course CSE281 offered
to the Department of BME instructed by Rifat Shahriyar, Professor, CSE, BUET (course link
).
4. search and all the sites that it made available in response to the course related
queries. Some of the sites are: https://geeksforgeeks.org/, https://www.tutorialspoint.com,
https://www.w3schools.com and the list goes on …
Thank You ☺

You might also like