File handling(some slides only)


Published on

Some function of file handling in C programming

Published in: Education
  • Be the first to comment

  • Be the first to like this

No Downloads
Total views
On SlideShare
From Embeds
Number of Embeds
Embeds 0
No embeds

No notes for slide

File handling(some slides only)

  1. 1. RANDOM ACCESS TO FILES• So far we have seen file functions that are useful for read and write data sequentially.• However, sometime we require to access only a particular part of a file.• This can be achieved using fseek , ftell and rewind function available in I/O library. 1
  2. 2. ftell• ftell takes a file pointer fp and return a number of type long, that corresponds to the current position. Example: n = ftell(fp);• n would give the relative offset (in bytes) of the current position. This means that n bytes have already been read (or written). 2
  3. 3. fseek• fseek function is used to move the file position to a desired location within the file. It takes the following form: fseek(file_ptr, offset, position);• file_ptr is a pointer to the file concerned.• offset is a number or variable of type long• position is an integer number• The offset specifies the number of positions (bytes) to be moved from the location specified by position.• The position can take one of the following three values: Value Meaning 0 Beginning of file 1 Current position 2 End of file 3
  4. 4. • When the operation is successful, fseek returns a zero.• If we attempt to move the file pointer beyond the file boundaries, an error occurs and fseek returns -1 (minus one). 4
  5. 5. rewind• Rewind takes a file pointer and resets the position to the start of the file.rewind(fp);n = ftell(fp);• Above two line code would assign 0 to n because the file position has been set to the start of the file by rewind. 5
  6. 6. • Remember, the first byte in the file is numbered as 0, second as 1, and so on.• Remember that whenever a file is opened for reading or writing, a rewind is done implicitly. 6
  7. 7. Statement Meaningfseek(fp,0L,0) Go to the beginning.(Similar to rewind).fseek(fp,0L,1) Stay at the current position(Rarely used).fseek(fp,0L,2) Go to the end of the file, past the last character of the file.fseek(fp,m,0) Move to (m+1)th byte in the filefseek(fp,m,1) Go forward by m bytesfseek(fp,-m,1) Go backward by m bytes from the current position.fseek(fp,-m,2) Go backward by m bytes from the end.(Position the file to the mth character from the end.) 7
  8. 8. Write a program that uses the functions ftell and fseek.#include <stdio.h>void main() { FILE *fp; long n; char c; fp = fopen("RANDOM", "w");while((c = getchar()) != EOF) putc(c,fp);printf("No. of characters entered = %ldn", ftell(fp)); fclose(fp);fp = fopen("RANDOM","r"); 8 n = 0L;
  9. 9. while(feof(fp) == 0){ fseek(fp, n, 0); /* Position to (n+1)th character */ printf("Position of %c is %ldn", getc(fp),ftell(fp)); n = n+5L; }putchar(n);fseek(fp,-1L,2); /* Position to the last character */ do { putchar(getc(fp)); }while(!fseek(fp,-2L,1)); fclose(fp); } 9
  10. 10. Output:ABCDEFGHIJKLMNOPQRSTUVWXYZ^ZNo. of characters entered = 26Position of A is 0Position of F is 5Position of K is 10Position of P is 15Position of U is 20Position of Z is 25Position of is 30ZYXWVUTSRQPONMLKJIHGFEDCBA 10
  11. 11. fgets• Reads count - 1 characters from the given file stream and stores them in str.• Characters are read until either a newline or an EOF is received or until the specified limit is reached.• Declaration: char *fgets( char *str, int count, FILE *stream );• Returns str on success or a NULL pointer on failure. 11
  12. 12. • Example of fgets:#include <stdio.h> sample.txt#include <stdlib.h> This is first line. This is second line and longer than first line. The End. void main() { FILE *fp; char str[128]; fp = fopen(“sample.txt", “r”); fgets(str, 126, fp); printf("%s", str); Output: fclose(fp); This is first line.} Note: Only first line displayed because new line occurred. 12
  13. 13. fputs• fputs writes text string to the stream. The strings null terminator is not written.• Declaration: int fputs(const char *str, FILE *stream);• Returns nonnegative on success and EOF on failure.• Example of fputs: void main() { FILE *fp; fp = fopen(“test.txt", "w”); fputs(“This is written to test file.", fp); fclose(fp); } 13
  14. 14. fflush• fflush empties the file io buffer and causes the contents to be written into the file immediately.• The buffer is a block of memory used to temporarily store data before actually writing it onto the disk.• The data is only actually written to the file when the buffer is full, the file stream is closed or when fflush() is called.• The fflush function returns zero if successful or EOF if an error was encountered. 14
  15. 15. rename• The function rename changes the name of the file oldfilename to newfilename.• Declaration:int rename(const char *old_filename, const char *new_filename )• It returns 0​ upon success and non-zero value on error.• Example of rename:#include <stdio.h> void main(){ int renameFile = 0; renameFile = rename("MYFILE.txt", "HELLO.txt"); if (renameFile != 0) printf("Error in renaming file."); getch(); } 15
  16. 16. remove• Deletes the file whose name is specified in filename.• Declaration: int remove ( const char * filename )• 0 is returned if file is successfully deleted and a nonzero value is returned on failure.#include <stdio.h>#include <conio.h>void main (){if ( remove("myfile.txt”) != 0 )printf( "Error deleting file" );elseprintf( "File successfully deleted" );getch();} 16
  17. 17. freopen• freopen() is used to redirect the system-defined files stdin, stdout and stderr to some other file.• Header file: stdio.h• Declaration: freopen(“filename”, “mode”, stream);• It Returns a pointer to stream on success or a null pointer on failure. 17
  18. 18. • Example of freopen: #include <stdio.h> #include <conio.h> void main() { FILE *fp; printf("This will display on the screen.n"); if((fp = freopen(“test.txt", "w" ,stdout)) == NULL) { printf("Cannot open file.n"); } printf("This will be written to the file OUT."); fclose(fp); } 18
  19. 19. ferror• ferror checks for a file error.• Header File: stdio.h• Declaration: int ferror(FILE *stream);• It returns 0 if no error has occurred and nonzero integer if an error has occurred.• ferror example: 19
  20. 20. • Example of ferror:#include <stdio.h>#include <conio.h>void main(){ FILE *fp; fp=fopen(“test.txt", “w") putc(C, fp); if(ferror(fp)) { printf("File Errorn"); } fclose(fp); } 20
  21. 21. fgetpos and fsetpos• fgetpos gets the file position indicator.• fsetpos moves the file position indicator to a specific location in a file.• Declaration: int fgetpos(FILE *stream, fpos_t *pos) – stream: A pointer to a file stream. – pos: A pointer to a file position.• They returns zero on success and nonzero on failure 21
  22. 22. • Example of fgetpos and fsetpos:#include <stdio.h>void main () { FILE *fp; fpos_t position;fp = fopen (“test.txt","w");fgetpos (fp, &position);fputs (“I like BCA", fp);fsetpos (fp, &position);fputs (“We“,fp);fclose (fp);} 22
  23. 23. Command line arguments• What is a command line argument? It is a parameter supplied to a program when the program is invoked.• main can take two arguments called argc and argv and the information contained in the command line is passed on to the program through these arguments, when main is called up by the system. main(int argc , char *argv[])• The variable argc is an argument counter that counts the number of arguments on the command line.• The argv is an argument vector and represents an array of character pointers that point to the command line arguments. 23
  24. 24. • Write a program that will receive a filename and a line of text as command line arguments and write the text to the file.• Explaination of programme:• Command line is:cmdl test AAAAAA BBBBBB CCCCCC DDDDDD EEEEEE FFFFFF GGGGGG• Each word in the command line is an argument to the main and therefore the total number of arguments is 9.• The argument vector argv[1] points to the string test and therefore the statement fp = fopen(argv[1], "w"); opens a file with the name test.• The for loop that follows immediately writes the remaining 7 arguments to the file test. 24
  25. 25. #include <stdio.h>void main(argc, argv) int argc; /* argument count */ char *argv[]; /* list of arguments */ { FILE *fp; int i; char word[15]; fp = fopen(argv[1], "w"); /* open file with name argv[1] */ printf("nNo. of arguments in Command line = %dnn", argc); for(i = 2; i < argc; i++) fprintf(fp,"%s ", argv[i]); /* write to file argv[1] */ fclose(fp); 25
  26. 26. /* Writing content of the file to screen */ printf("Contents of %s filenn", argv[1]); fp = fopen(argv[1], "r"); for(i = 2; i < argc; i++) { fscanf(fp,"%s", word); printf("%s ", word); } fclose(fp); printf("nn");/* Writing the arguments from memory */ for(i = 0; i < argc; i++) printf("%*s n", i*5,argv[i]); } 26
  27. 27. Output:C:> cmdl test AAAAAA BBBBBB CCCCCC DDDDDD EEEEEE FFFFFF GGGGG No. of arguments in Command line = 9 Contents of test file AAAAAA BBBBBB CCCCCC DDDDDD EEEEEE FFFFFF GGGGGGC:>cmdl.EXE //This is argv[0] TEXT //This is argv[1] AAAAAA //This is argv[2] BBBBBB CCCCCC DDDDDD EEEEEE FFFFFF GGGGGG 27
  28. 28. 28