FILE INPUT / OUTPUT Dong-Chul Kim BioMeCIS CSE @ UTA Whats a file? - - PowerPoint PPT Presentation

file input output
SMART_READER_LITE
LIVE PREVIEW

FILE INPUT / OUTPUT Dong-Chul Kim BioMeCIS CSE @ UTA Whats a file? - - PowerPoint PPT Presentation

7/21/2014 1 FILE INPUT / OUTPUT Dong-Chul Kim BioMeCIS CSE @ UTA Whats a file? A named section of storage, usually on a disk In C, a file is a continuous sequence of bytes Examples for the demand of a file in C programming:


slide-1
SLIDE 1

FILE INPUT / OUTPUT

Dong-Chul Kim BioMeCIS CSE @ UTA

7/21/2014

1

slide-2
SLIDE 2
  • A named section of storage, usually on a disk
  • In C, a file is a continuous sequence of bytes
  • Examples for the demand of a file in C programming:
  • Grade calculation
  • Friend recommendation on Facebook

What’s a file?

slide-3
SLIDE 3
  • C programs automatically open three files for you, namely the

standard input, standard output, and the standard error output.

  • standard input – the normal input device for your system, e.g.,

keyboard

  • scanf(), getchar(), gets()
  • standard output and standard output error – the normal output device

for your system, e.g., display screen

  • printf(), putchar(), puts()

Standard files

slide-4
SLIDE 4
  • Prototype: char * gets (char * str );
  • Reads characters from stdin and stores them as a string into str until a newline

character ('\n').

  • The ending newline character ('\n') is not included in the string.
  • A null character ('\0') is automatically appended after the last character copied to

str to signal the end of the C string.

  • Notice that gets() does not let you specify a limit on how many characters are to

be read, so you must be careful with the size of the array pointed by str to avoid buffer overflows.

  • The return data:
  • If gets() is called successfully, it returns the same str parameter, which means “ print out

(gets(str)) == print out str “

  • If no characters have been read, the contents of str remain unchanged and a null pointer is

returned.

  • If an error occurs, a null pointer is returned.

gets( )

slide-5
SLIDE 5

#include <stdio.h> int main(void) { char mych[41]; //printf("Please intput a string with characters less than 40:\n"); puts("Please intput a string with characters less than 40:\n"); gets(mych); puts(mych); return 0; }

  • Note that all input will be regarded as one string.

However, scanf(“%s”, mych) will only read the characters until the first space as one string.

gets() and puts( )

slide-6
SLIDE 6
  • When working with files in C, declare a FILE variable
  • The FILE variable needs to be a pointer, because it is a

pointer to a file

  • FILE * fp

File Operation in C Program

slide-7
SLIDE 7
  • FILE * fopen (char * filename, char * mode );
  • Specify the file path and the mode
  • If successful, fopen returns a file pointer; otherwise,

NULL is returned:

  • a file we wish to read may not exist
  • a file we wish to write to may be in use by another program

Associate the variable with a file

mode Function

"r" Open a file for reading. The file must exist. "w" Create an empty file for writing. If a file with the same name already exists its content is erased and the file is treated as a new empty file. "a" Append to a file. Writing operations append data at the end of the file. The file is created if it does not exist. "r+" Open a file for update both reading and writing. The file must exist. "w+" Create an empty file for both reading and writing. If a file with the same name already exists its content is erased and the file is treated as a new empty file. "a+" Open a file for reading and appending. All writing operations are performed at the end of the file, protecting the previous content to be overwritten. You can reposition the internal pointer to anywhere in the file for reading, but writing operations will move it back to the end of file. The file is created if it does not exist.

slide-8
SLIDE 8
  • A file name is nothing but string, so we can use strcat() to form a complex name.

#include <stdio.h> #include <stdlib.h> int main(void) { char fn[20]="";/*Without "", you will encounter an error on VS 2008, when you call strcat(). This is because fn is not a string without the initialization by “” – a string has to have the null character ‘\0’. */ char prefn[] = "myfile"; char exfn[] = ".txt"; char index[5];/*ranging from a to z*/ FILE * fp; scanf("%s",index); strcat(fn, prefn); printf("%s\n",fn); strcat(fn,index); printf("%s\n",fn); strcat(fn, exfn); printf("%s\n",fn); fp = fopen(fn, "w"); fclose(fp); return 0; }

Flexibility of File Names

slide-9
SLIDE 9
  • To read in or write out text by character, use getc( ) and putc( )
  • int getc ( FILE * stream );
  • returns the char, or EOF (the end of the file)
  • ch = getchar() is equivalent to ch = getc(stdin)
  • int putc ( int character, FILE * stream );
  • If there are no errors, the same character that has been written is returned.
  • If an error occurs, EOF is returned and the error indicator is set.
  • putchar(ch) is equivalent to putc(ch,stdout), given
  • char ch = ‘a’;
  • Both in stdio.h

Writing / Reading by single character

slide-10
SLIDE 10
  • EOF indicates the end of the file
  • To check for the end of the file, two approaches
  • use (ch = getchar()) == EOF
  • int feof ( FILE * stream );

A non-zero value is returned in the case that the End-of-File indicator associated with the stream is set. Otherwise, a zero value is returned.

  • Included in stdio.h

The End of File EOF

slide-11
SLIDE 11

#include <stdio.h> #include <stdlib.h> int main(void) { int ch; FILE * fp; fp = fopen("myfile.txt","r"); ch = getc(fp); while(ch != EOF) { putchar(ch); ch = getc(fp); } return 0; }

slide-12
SLIDE 12
  • char * fgets ( char * str, int num, FILE * stream );
  • Reads characters from stream and stores them as a C string into str

until

  • (num-1) characters have been read
  • or either newline
  • or a the End-of-File is reached, whichever comes first.
  • A newline character makes fgets stop reading, but it is considered a

valid character and therefore it is included in the string copied to str.

  • A null character is automatically appended in str after the characters

read to signal the end of the C string.

Writing / Reading by line of text

slide-13
SLIDE 13
  • Return data
  • On success, the function returns the same str parameter.
  • If the End-of-File is encountered and no characters have been

read, the contents of str remain unchanged and a null pointer is returned.

  • If an error occurs, a null pointer is returned.
slide-14
SLIDE 14

#include <stdio.h> #include <stdlib.h> int main(void) { char fn[20]="myfile21.txt"; char buffer[100] = "";/*Note!!!*/ FILE * fp = fopen(fn, "r"); fgets(buffer, 50, fp);

printf("The number of characters in the file is %d.\n", strlen(buffer));

fclose(fp); return 0; }

slide-15
SLIDE 15
  • exit() function causes the program to terminate, closing

any open files.

  • Passing a value of zero for programs that terminate

normally, and a non-zero value for abnormal termination

  • Different from return, for a recursive program, return will

pass flow control to the previous level of recursion until the original level is reached. exit() still terminates the program.

exit()

slide-16
SLIDE 16
  • Use fclose() when you are finished working with the files
  • int fclose ( FILE * stream );
  • Return Value
  • If the stream is successfully closed, a zero value is returned.

On failure, EOF is returned.

fclose( )

slide-17
SLIDE 17

#include <stdio.h> #include <stdlib.h> int main(void) { int ch; FILE * fp; long count = 0; fp = fopen("myfile.txt", "w");/*"r"*/ //fp = fopen("c:\\myfile.txt", "w"); /*By default, the file will be created in the project folder.*/ if (fp == NULL) { printf("Can't open myfile.txt.\n"); exit(1); /*exit()*/ } ch = getc(fp); /*getc*/ while (ch != EOF) /*EOF*/ { putc(ch, stdout); /*putc()*/ count++; } fclose(fp); /*fclose()*/ printf("File myfile.txt has %d characters\n", count); return 0; }