File connection File connection
(Text File)
(Text File)
Topics Topics
• File types
• Opening files
• Closing files
• Reading from files
• Writing to files
• File pointer manipulations
• Files deletion and rename
2
Why Why
programming programming
with files with files
• Files can save all information Files can save all information once the program terminated once the program terminated
• Results from your program Results from your program can easily saved into files can easily saved into files
• Input bulk data from Input bulk data from
keyboard input can be the keyboard input can be the
most tedious job to do
most tedious job to do
Streams Streams
• Streams are flows of information
• File is one type of stream to either receive or send information
• Stream type
o Text Streams o Binary Streams
4
Streams Streams
• Text Streams
o Storing data in a form of ASCII
o New line can be stored using additional ASCII codes
• Carriage-return
• Linefeed
o Example files are .c, .txt, .bat
• Binary Streams
o Storing each data in 1 byte
o Example files type are .exe, .com, .obj
• EOF is used to end the files which can be checked with an feof() command
File manipulation File manipulation
• Orders of manipulation
o Open the files
o Files read/write/etc.
o Closing the files
• A pointer will be used to identify a file to be used for reading/writing.
6
File declaration File declaration
• FILEFILE
data type similar to int, char data type similar to int, char
• *fp *fp a variable name of a filea variable name of a file
FILE *fp;
FILE *fp;
Since C is case sensitive, all letter of the word “FILE “ are required to be
capitalised.
Opening Opening
the file the file
• fpfp the name of a file pointer (after the name of a file pointer (after declaring FILE *fp;)
declaring FILE *fp;)
• fopenfopen A file opening commandA file opening command
• file namefile name Name (and extension) of a file you Name (and extension) of a file you will use
will use
• modemode Mode in which to used the file for, Mode in which to used the file for, e.g. read, write
e.g. read, write
8
fp = fopen(“file name”,“mode”);
fp = fopen(“file name”,“mode”);
Managing a File Managing a File
• fopen() in stdio.h usage
FILE *fopen(char *fname,char *mode);
Example
FILE *fp;
if ((fp = fopen("myfile","r")) == NULL) { printf("Error opening file \n");
exit(1);
}
Managing a File Managing a File
Mode How it works
r Opening the text file for reading only
w Opening the text file for writing. If the file exists, the will be replaced.
a Appending(add to the end) the text file.
The file will be created if not exist.
r+ Opening the text file for reading and writing
w+ Opening the text file for writing. If the file exists, the will be replaced.
a+ Appending(add to the end) the text file.
The file will be created if not exist.
10
‘+’ mode can be used with rewind(fp);ter“t” เพิ่ม เข้าไปใน mode ด้วย (rt, w+t เป็นต้น)
สำาหร ับการทำางานก ับ Binary File เราต้องใส่อ ักษร “b” เพิ่ม เข้าไปใน mode ด้วย (wb, a+b เป็นต้น) )
Managing a File Managing a File
• NULL will be returned if the file cannot be opened
• fclose() is used for closing the file (stdio.h)
int fclose(FILE *fp)
• remove() is used for deleting the file int remove(char *file-name)
• rename() is used for changing the file name
int rename(char *oldname, char *newname)
Commands for text Commands for text
files files
• Read/Write 1 Byte at a time to a file
int fgetc(FILE *fp)
int fputc(int ch, FILE *fp)
• Read/write more than 1 Byte
char *fgets(char *str, int num, FILE *fp) int fputs(char *str, FILE *fp)
int fprintf(FILE *fp, char *cont_string,..) int fscanf(FILE *fp, char *cont_string,..)
12
Reading from a Reading from a
text file text file
• fscanffscanf CommandCommand
• fpfpFile pointerFile pointer
• fnamefname The first string will be strored in the The first string will be strored in the variable
variable
• Lname Lname The second string(after a white space) The second string(after a white space) will be stored here
will be stored here
fscanf (fp, "%s %s", fname, lname);
fscanf (fp, "%s %s", fname, lname);
Reading from a Reading from a
text file text file
• JakkapanJakkapan will be in will be in fnamefname
• MadeetrakulMadeetrakul will be in will be in lnamelname
14
fscanf (fp, "%s %s", fname, lname);
fscanf (fp, "%s %s", fname, lname);
In this case, strings from an example file In this case, strings from an example file
will be stored as followed will be stored as followed
Jakkapan Madeetrakul Jakkapan Madeetrakul
Reading numeric data will first be read as string and cast it to int/float later
Writing a Text Writing a Text
File File
fprintf (fp, "%s %d", name, age);
fprintf (fp, "%s %d", name, age);
Writing to a Writing to a
Text File Text File
16
fprintf (fp, "%s %d", name, age);
fprintf (fp, "%s %d", name, age);
In this example if name is having In this example if name is having the value “Teera” while age is
the value “Teera” while age is 30 30 A text file will be
A text file will be
Teera 30
Teera 30
Writing to a Writing to a
Text File Text File
After writing to a text file all data After writing to a text file all data types(int,float) will becom strings types(int,float) will becom strings
fprintf (fp, "%s\t%d", name, age);
fprintf (fp, "%s\t%d", name, age);
For example For example
Text file will become Text file will become Teera
Teera 30 30
*****Reading and writing requires the same
format type*****
• Entering a text file by inserting Entering a text file by inserting name,age,gpa in a text file
name,age,gpa in a text file
• Run a program again to see the Run a program again to see the result
result
18
Writing a data on Writing a data on
a text file a text file
typedef struct{
char name[20];
int age;
float gpa;
}stu;
void main(){
stu r[5];
FILE *fp;
char a[20];
fp = fopen("C:/Users/admin/Documents/1.txt","w");
for(int i=0;i<2;i++){
printf("Enter name:");
scanf("%s",r[i].name);
printf("Enter age:");
scanf("%d",&r[i].age);
printf("Enter gpa:");
scanf("%f",&r[i].gpa);
fprintf(fp,"%s %d %.2f\n",r[i].name,r[i].age,r[i].gpa);
}
Reading text from Reading text from
file and print on file and print on
the screen the screen
void main(){
stu r[5];
FILE *fp;
fp = fopen("C:/Users/admin/Documents/1.txt","r");
while(!feof(fp)){
fscanf(fp,"%s %d %f",r[0].name,&r[0].age,&r[0].gpa);
if(!feof(fp)) printf("%s %d %.2f\n",r[0].name,r[0].age,r[0].gpa);
}
20
Reading each Reading each character from file character from file
and print on the and print on the
screen screen
void main(){
char a;
FILE *fp;
fp = fopen("C:/Users/admin/Documents/1.txt","r");
while(!feof(fp)){
a=fgetc(fp);
if(!feof(fp)) printf("%c”,a);
} }
#include "stdio.h"
#include "stdlib.h"
void main() {
FILE *fp;
int i;
if ((fp = fopen("myfile.txt","r"))==NULL) { /* opening myfile for reading */
printf("Can not open file.");
exit(1);
}
for(;;) { /* loop*/
i = fgetc(fp); /* read each byte to i*/
if(i==EOF) break; /* read till the end*/
putchar(i); /* Print to the screen*/
}
fclose(fp); /* close fp */
}
Example Using fgetc to read myfile
22
Write each Write each character to file character to file
void main(){
char a[]=“Mahidol university”;
FILE *fp;
fp = fopen("C:/Users/admin/Documents/1.txt",“w");
for(int i=0;i<strlen(a);i++) fputc(a[i],fp);
}
#include "stdio.h"
#include "stdlib.h"
char str[80] = "This is a file system test"; /* text for writing*/
void main() {
FILE *fp;
char *p;
if ((fp = fopen("myfile.txt","w"))==NULL) { /* opening myfile for writing*/
printf("Can not open file.");
exit(1);
}
p = str; /* p points to str*/
while (*p) { /* loop for writing*/
if (fputc(*p,fp)==EOF) { /* Write each Byte to the file */
printf("Error writing file\n");
exit(2);
}
p++; /* move Pointer p one position at a time*/
}
fclose(fp); /* closing file*/
}
Example Using fputc to write"This is a file system test" to myfile
#include "stdlib.h"
#include "stdio.h"
void main(void) {
int i;
FILE *fp;
if ((fp = fopen("test.txt", "w"))==NULL) { printf("File could not be opened.");
exit(1);
}
for (i=1;i<=10;i++)
fprintf(fp, "this is a test %d * %d = %d\n", i, i, i*i);
fclose(fp);
}
24
ต ัวอย่าง Writing to test
Writing to a file Writing to a file
• 1
• 3
• 6
• 10
• 15
• …
#include "stdlib.h"
#include "stdio.h"
void main(void)
{ char str[81];
FILE *fp;
if ((fp = fopen("test.txt","r"))==NULL) { printf("File could not be opened.");
exit(1);
}
while (!feof(fp)) { if (fgets(str,80,fp)) printf("%s", str);
}
fclose(fp);
}
26
Example Reading from a file test.txt and print to the screen
#include "stdio.h"
void main() {
int account;
char name[30];
float balance;
FILE *cfPtr;
if ((cfPtr = fopen("client.dat","w"))==NULL) { printf("File could not be opened.");
} else {
printf("Enter the account ,name and balance \n ctrl+z for exit.\n");
printf("? ");
scanf("%d%s%f", &account, name, &balance);
while (!feof(stdin)) { fprintf(cfPtr,"%d %s %.2f\n", account, name, balance);
printf("? ");
scanf("%d%s%f", &account, name, &balance);
}
fclose(cfPtr);
}
return;
Example reading from the screen and put in a text file
#include "stdio.h"
void main() {
int account;
char name[30];
float balance;
FILE *cfPtr;
if ((cfPtr = fopen("client.dat","r"))==NULL) { printf("File could not be opened.");
} else {
printf("%-10s %-13s %s\n", "Account", "Name", "Balance");
fscanf(cfPtr,"%d%s%f", &account, name, &balance);
while (!feof(cfPtr)) {
printf("%-10d %-13s %7.2f\n", account, name, balance);
fscanf(cfPtr, "%d%s%f", &account, name, &balance);
}
fclose(cfPtr);
}
return;
}
28
Example Read file from client