file input output
play

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:


  1. 7/21/2014 1 FILE INPUT / OUTPUT Dong-Chul Kim BioMeCIS CSE @ UTA

  2. What’s 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: • Grade calculation • Friend recommendation on Facebook

  3. Standard files • 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()

  4. gets( ) • 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.

  5. gets() and puts( ) #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.

  6. File Operation in C Program • 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

  7. Associate the variable with a file • 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 mode Function "r" Open a file for reading. The file must exist. Create an empty file for writing. If a file with the same name already exists its content is erased "w" and the file is treated as a new empty file. Append to a file. Writing operations append data at the end of the file. The file is created if it "a" does not exist. "r+" Open a file for update both reading and writing. The file must exist. Create an empty file for both reading and writing. If a file with the same name already exists its "w+" content is erased and the file is treated as a new empty file. 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 "a+" 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.

  8. Flexibility of File Names • 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; }

  9. Writing / Reading by single character • 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

  10. The End of File EOF • 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

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

  12. Writing / Reading by line of text • 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.

  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.

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

  15. exit() • 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.

  16. fclose( ) • 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.

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

Download Presentation
Download Policy: The content available on the website is offered to you 'AS IS' for your personal information and use only. It cannot be commercialized, licensed, or distributed on other websites without prior consent from the author. To download a presentation, simply click this link. If you encounter any difficulties during the download process, it's possible that the publisher has removed the file from their server.

Recommend


More recommend