• No results found

(Text File)

N/A
N/A
Protected

Academic year: 2022

Share "(Text File)"

Copied!
30
0
0

Loading.... (view fulltext now)

Full text

(1)

File connection

(Text File)

(2)

Topics

• File types

• Opening files

• Closing files

• Reading from files

• Writing to files

• File pointer manipulations

• Files deletion and rename

(3)

Why programming with files

Files can save all information once the program terminated

Results from your program can easily saved into files

Input bulk data from keyboard input can be the

most tedious job to do

(4)

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

(5)

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

(6)

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.

(7)

File declaration

• FILE data type similar to int, char

• *fp a variable name of a file

FILE *fp;

Since C is case sensitive, all letter of the word “FILE “ are required to be capitalised.

(8)

Opening the file

fp the name of a file pointer (after declaring FILE *fp;)

fopen A file opening command

file name Name (and extension) of a file you will use

mode Mode in which to used the file for, e.g. read, write

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

(9)

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

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

• 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 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,..)

(13)

Reading from a text file

fscanf Command

fp File pointer

fname The first string will be strored in the variable

Lname The second string(after a white space) will be stored here

fscanf (fp, "%s %s", fname, lname);

(14)

Reading from a text file

• Jakkapan will be in fname

• Madeetrakul will be in lname

fscanf (fp, "%s %s", fname, lname);

In this case, strings from an example file will be stored as followed

Jakkapan Madeetrakul

Reading numeric data will first be read as string and cast it to int/float later

(15)

Writing a Text File

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

(16)

Writing to a Text File

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

In this example if name is having the value “Teera” while age is 30 A text file will be

Teera 30

(17)

Writing to a Text File

After writing to a text file all data types(int,float) will becom strings

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

For example

Text file will become

Teera 30

(18)

• Entering a text file by inserting name,age,gpa in a text file

• Run a program again to see the result

Writing a data on 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 file and print on 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 character from file and print on the 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*/

Example Using fgetc to read myfile

(22)

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

}

ต ัวอย่าง Writing to test

(25)

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)) { fprintf(cfPtr,"%d %s %.2f\n", account, name, balance);

printf("? ");

scanf("%d%s%f", &account, name, &balance);

}

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;

}

Example Read file from client

(29)
(30)

Question ?

References

Related documents

Arkansas Tech University Auburn University Augusta State University Baylor University Bluefield State College Clemson University Coastal Carolina University Delaware State

Create a text file on the desktop called Backup File One.. Open the file and type the text “The text in this file will not

Create a text file on the desktop called Backup File One.. Open the file and type the text “The text in this file will not

Consideration of Proctor reveals at least three major problems with the approach of the Stop the Beach plurality. First, the plurality does not clarify whether it is essential for

From a review of loan application documents collected by survey volunteers for some payday and auto title locations, it was also possible to partially assess compliance with a

The study showed RGO deposited on silicon as a heat spreader could help to reduce the effect of heat generated in the Schottky junction that leads to a leakage current reduction

Abbreviations: EEVS, endothelial-derived microvesicles; ELISA, enzyme linked immune-sorbent assays; EVS, extracellular vesicles; EXS, exosomes; DSL, dynamic light scattering;

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