• No results found

(Text File)(Text File)

N/A
N/A
Protected

Academic year: 2022

Share "(Text File)(Text File)"

Copied!
30
0
0

Loading.... (view fulltext now)

Full text

(1)

File connection File connection

(Text File)

(Text File)

(2)

Topics Topics

• File types

• Opening files

• Closing files

• Reading from files

• Writing to files

• File pointer manipulations

• Files deletion and rename

2

(3)

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 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

(5)

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

(6)

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

(7)

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

8

fp = fopen(“file name”,“mode”);

fp = fopen(“file name”,“mode”);

(9)

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);

}

(10)

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 เป็นต้น) )

(11)

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)

(12)

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

(13)

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);

(14)

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

(15)

Writing a Text Writing a Text

File File

fprintf (fp, "%s %d", name, age);

fprintf (fp, "%s %d", name, age);

(16)

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

(17)

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*****

(18)

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);

}

(19)

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)

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);

} }

(21)

#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)

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);

}

(23)

#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

(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);

}

24

ต ัวอย่าง Writing to test

(25)

Writing to a file 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);

}

26

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)) { 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;

}

28

Example Read file from client

(29)
(30)

Question ?

Question ?

References

Related documents

1) Create Excel File with 13 columns as described in above table. 2) Save excel file as CSV (Comma Separated Value MS-DOS) 3) Open CSV in text editor like Notepad / Wordpad etc..

A file wrapper stores file system information (such as modification time and access permissions), which it updates when reading from disk and uses when writing files to disk..

If on uploading a text file, we are getting a message which says that error on line number X which is one more than no of records in KYC text file, it implies that we have left a

The rotor to open applications that will need to custom crossword puzzle directly in available text file with instructions crossword.. Would Sauron have honored the terms offered by

Store which file not vba write text file and saves the system object using excel vba file which represents the analytics and even from a formula!. Administrator and write to

Multiple causes (Error opening i-gen.fls for reading, Error opening isogen.fls for writing, Error opening options file specified in i-gen.fls, Error closing options file specified

There any many different sheets within a vba code to read input function to getting value of these cookies to excel vba append text file name?. Dim text

and marks of five students and display them on screen after reading from the text file using data file handling... /* Wap in c++ to create a binary file binary file binary