File Management in C
Files
• File – place on disc where group of related data is stored
– E.g. your C programs, executables
• High-level programming languages support file operations
– Naming
– Opening
– Reading
– Writing
– Closing
Defining and opening file
• To store data file in secondary memory (disc) must specify to
OS
– Filename (e.g. sort.c, [Link])
– Data structure (e.g. FILE)
– Purpose (e.g. reading, writing, appending)
General format for opening file
FILE *fp; /*variable fp is pointer to type FILE*/
fp = fopen(“filename”, “mode”);
/*opens file with name filename , assigns identifier to fp */
• fp
– contains all information about file
– Communication link between system and program
• Mode can be
– r open file for reading only
– w open file for writing only
– a open file for appending (adding) data
Different modes
• Writing mode
– if file already exists then contents are deleted,
– else new file with specified name created
• Appending mode
– if file already exists then file opened with contents safe
– else new file created
• Reading mode
– if file already exists then opened with contents safe
– else error occurs.
FILE *p1, *p2;
p1 = fopen(“data”,”r”);
p2= fopen(“results”, w”);
All Modes
Mode Description
r Opens an existing text file for reading purpose.
Opens a text file for writing. If it does not exist, then a new file is created. Here your
w program will start writing content from the beginning of the file.
Opens a text file for writing in appending mode. If it does not exist, then a new file
a is created. Here your program will start appending content in the existing file
content.
r+ Opens a text file for both reading and writing.
Opens a text file for both reading and writing. It first truncates the file to zero length
w+ if it exists, otherwise creates a file if it does not exist.
Opens a text file for both reading and writing. It creates the file if it does not exist.
a+ The reading will start from the beginning but writing can only be appended.
Closing a file
• File must be closed as soon as all operations on it completed
• Ensures
– All outstanding information associated with file flushed out from
buffers
– All links to file broken
– Accidental misuse of file prevented
• If want to change mode of file, then first close and open again
Closing a file
Syntax: fclose(file_pointer);
Example:
FILE *p1, *p2;
p1 = fopen(“[Link]”, “r”);
p2 =fopen(“[Link]”, “w”);
……..
……..
fclose(p1);
fclose(p2);
• pointer can be reused after closing
Input/Output operations on files
• C provides several different functions for reading/writing
• getc() – read a character
• putc() – write a character
• fprintf() – write set of data values
• fscanf() – read set of data values
• getw() – read integer
• putw() – write integer
fscanf() and fprintf()
• similar to scanf() and printf()
• in addition provide file-pointer
• given the following
– file-pointer f1 (points to file opened in write mode)
– file-pointer f2 (points to file opened in read mode)
– integer variable i
– float variable f
• Example:
fprintf(f1, “%d %f\n”, i, f);
fprintf(stdout, “%f \n”, f); /*note: stdout refers to screen */
fscanf(f2, “%d %f”, &i, &f);
• fscanf returns EOF when end-of-file reached
Write a C program to write your name 5 times to a file
#include <stdio.h>
void main(){
FILE *fl;
char filename[50]="[Link]";
int i; 1->TARKAN
fl=fopen(filename,"w"); 2->TARKAN
3->TARKAN
for(i=1;i<=5;i++) 4->TARKAN
5->TARKAN
{
fprintf(fl,"%d->TARKAN\n",i);
}
fclose(fl); }
Açma Modu: “w” write (yazma), “r” read (okuma), “a” append (ekleme), “w+”,
“r+” ve “a+” hem okuma hem yazma, “b” binary (ikili, diğerleri ile birlikte kullanılır:
“w+b” gibi)
Write a C program to print from a text file to screen
#include <stdio.h> CONTENT OF THE TEXT FILE
void main(){ Kocaeli
FILE *fl; University
char filename[50]="[Link]"; Electronics
char val[50]; and
Communication
fl=fopen(filename,"r"); Department
while (!feof(fl))
{
fscanf(fl,"%s",val);
printf("%s\n",val);
}
fclose(fl);
}
feof() :Dosya sonuna gelinmediği fscanf komutu yerine fgetc fonksiyonu
sürece tüm kayıtları tarar. feof da dosyadan bir karakter (byte) veri
fonksiyonu dosya sonuna gelinince true okumada aşağıdaki gibi kullanılabilir.
değer döndürür. printf("%c", fgetc(dosya));
EXACT SAME FROM FILE
int main(int argc, char *argv[]) { CONTENT OF THE TEXT FILE
FILE *fp; This is about programming
fp=fopen("[Link]","r"); It is written by Enrich
char arr[100],c; Enrich is developer
while(!(feof(fp)))
{
c=fgetc(fp);
printf("%c",c);
}
while(!(feof(fp)))
{
c=getc(fp);
printf("%c",c);
}
while(!(feof(fp)))
{
fscanf(fp,"%s",arr);
printf("%s\n",arr);
}
C program to read data from keyboard and write it to a text file
#include <stdio.h>
#include <string.h>
void main(){
FILE *fl;
char filename[50]="[Link]";
char val[50];
int i;
fl=fopen(filename,"w");
do
{
gets(val);
fprintf(fl,"\n%s",val);
}while(strlen(val));
fclose(fl);}
scanf kullanımı boşluk str = "" olduğunda strlen sıfır
karakterinde sorun çıkardığı için döndürür. while(0) döngüden çıkış
gets kullandık anlamına gelir.
getc() and putc()
• handle one character at a time like getchar() and putchar()
• syntax: putc(c,fp1);
– c : a character variable
– fp1 : pointer to file opened with mode w
• syntax: c = getc(fp2);
– c : a character variable
– fp2 : pointer to file opened with mode r
• file pointer moves by one character position after every getc()
and putc()
• getc() returns end-of-file marker EOF when file end reached
Program to read/write using getc/putc
#include <stdio.h>
main(){
FILE *f1;
char c;
f1= fopen("[Link]", "w"); /* open file for writing */
while((c=getchar()) != EOF) /*get char from keyboard until CTL-Z*/
putc(c,f1); /*write a character to INPUT */
fclose(f1); /* close INPUT */
f1=fopen("[Link]", "r"); /* reopen file */
while((c=getc(f1))!=EOF) /*read character from file INPUT*/
printf("%c", c); /* print character to screen */
fclose(f1);
return 0;
} /*end main */
C program to Copy the contents of one file into another
#include <stdio.h>
void main(){
FILE *fl1,*fl2;
char filenameWR[50]="[Link]";
char filenameRD[50]="[Link]";
char val;
fl1=fopen(filenameRD,"r"); fl2=fopen(filenameWR,"w");
while(1)
{
val=getc(fl1);
putc(val,fl2);
if(feof(fl1))
{ break; }
} while (!feof(d1))
fclose(fl1); fputc(fgetc(d1), d2);
fclose(fl2);}
Yukarıdaki kullanım d2'ye eof karakterini
de yazar. Yani d2 dosyası, d1 dosyasından
1 byte fazla olur.
Alternative Two Ways for The Copy
FILE *fp1,*fp2; FILE *fp1,*fp2;
char c; char data[100];
fp1=fopen("[Link]","r");
fp1=fopen("[Link]","r");
fp2=fopen(“[Link]","w");
fp2=fopen("[Link]","w");
while((c=getc(fp1))!=EOF) while(!feof(fp1))
{ {
putchar(c); //To screen fscanf(fp1,"%s",data);
putc(c,fp2);
fprintf(fp2,"%s\n",data);
}
}
fclose(fp1); fclose(fp1);
fclose(fp2); fclose(fp2);
File
operatio Declaration & Description
n
putw() Declaration: int putw(int number, FILE *fp);
putw function is used to write an integer into a file. In a C program, we can write
integer value in a file as below.
putw(i, fp);
where
i – integer value
fp – file pointer
getw() Declaration: int getw(FILE *fp);
getw function reads an integer value from a file pointed by fp. In a C program, we
can read integer value from a file as below.
getw(fp);
• Handle one integer at a time
• File pointer moves by one integer position, data stored in binary format native to local
system
• getw() returns end-of-file marker EOF when file end reached
How To Write Into A File Using putw() Function
How To Read The Same File Using getw() Function.
If(num!=-1)
FILE *fp;
int n1=10,n2=20,n3=30;
int num;
fp=fopen("[Link]","w");
putw(n1,fp);
putw(n2,fp); while(!feof(fp))
putw(n3,fp); {
fclose(fp);
num=getw(fp);
fp=fopen("[Link]","r"); printf("%d\n",num);
while(!feof(fp)) }
{
num=getw(fp);
if(num!=EOF)
printf("%d\n",num);
}
fclose(fp);
C program using getw, putw,fscanf, fprintf
#include <stdio.h> #include <stdio.h>
main() main()
{ int i,sum1=0; { int i, sum2=0;
FILE *f1; FILE *f2;
/* open files */ /* open files */
f1 = fopen("int_data.bin","w"); f2 = fopen("int_data.txt","w");
/* write integers to files in binary /* write integers to files in binary and
and text format*/ text format*/
for(i=10;i<15;i++) putw(i,f1); for(i=10;i<15;i++) printf(f2,"%d\n",i);
fclose(f1); fclose(f2);
f1 = fopen("int_data.bin","r"); f2 = fopen("int_data.txt","r");
while((i=getw(f1))!=EOF) while(fscanf(f2,"%d",&i)!=EOF)
{ sum1+=i; { sum2+=i; printf("text file:
printf("binary file: i=%d\n",i); i=%d\n",i);
} /* end while getw */ } /*end while fscanf*/
printf("binary sum=%d,sum1); printf("text sum=%d\n",sum2);
fclose(f1); fclose(f2);
} }
On execution of previous Programs
$ ./[Link] $ ./[Link]
binary file: i=10 text file: i=10
binary file: i=11 text file: i=11
binary file: i=12 text file: i=12
text file: i=13
binary file: i=13
text file: i=14
binary file: i=14 text sum=60
binary sum=60, $ more int_data.bin
$ cat int_data.txt ^@^@^@^K^@^@^@^L^@^@^@^
M^@^@^@^N^@^@^@
10
$
11
12
13
14