File connection
(Text File)
2
File types
Opening files
Closing files
Reading from files
Writing to files
File pointer manipulations
Files deletion and rename
Topics
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
4
Streams are flows of information
File is one type of stream to either receive or send information
Stream type
Text Streams
Binary Streams
Streams
Text Streams
Storing data in a form of ASCII
New line can be stored using additional ASCII codes
Carriage-return
Linefeed
Example files are .c, .txt, .bat
Binary Streams
Storing each data in 1 byte
Example files type are .exe, .com, .obj
EOF is used to end the files which can be checked with an feof() command
Streams
6
File manipulation
Orders of manipulation
Open the files
Files read/write/etc.
Closing the files
A pointer will be used to identify a file to be used for reading/writing.
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.
8
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
fp = fopen(“file name”,“mode”);
fp = fopen(“file name”,“mode”);
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
10
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.
Managing a File
For Text File, the letter“t” เพิ่มเข้าไปใน mode ด้วย (rt, w+t เป็นต้น)
สำาหร ับการทำางานก ับ Binary File เราต้องใส่อ ักษร “b” เพิ่ม เข้าไปใน mode ด้วย (wb, a+b เป็นต้น) )
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)
Managing a File
12
Commands for text 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,..)
Example
char name[20];
mode "r"
name[0]=fgetc(fp);
fgets(name,19,fp);
fscanf(fp,"%s",name);
mode "w" ,"a"
fputc(name[0],fp);
fputs(name,fp);
fprintf(fp,"%s",name);
14
Reading from a Reading from a
text file text file
fscanffscanf CommandCommand
fpfp File pointerFile pointer
fnamefname The first string will be strored in The first string will be strored in the variable
the variable
lnamelname The second string(after a white The second string(after a white space) will be stored here
space) 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
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
16
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
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
18
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*****
Experiment of Experiment of
writing a text file writing a text file
An example program can be done byAn example program can be done by
After running the program, check if “data.txt” After running the program, check if “data.txt”
is created is created
20
Entering a text file by inserting name,age,gpa in a text fileEntering a text file by inserting name,age,gpa in a text file
Run a program again to see the resultRun a program again to see the result
Writing a data on Writing a data on
a text file
a text file
Reading a text file Reading a text file
and print on the and print on the
screen
screen
22
#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 "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 */
}
ต ัวอย่าง Using fgetc to read myfile
24
#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);
}
ต ัวอย่าง Writing to test
Writing to a file
1
3
6
10
15
…
26
#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);
}
Example Reading from a file test.txt and print to the screen
27
#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)) { /* stdin คือแป้มพิมพ์
และ ctrl+z คือบอกสิ้นสุดการป้อนข ้อมูล*/
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
28
#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;
}
ต ัวอย่าง Read file from client