Mesics lecture files in 'c'

2,487 views

Published on

File Handling in 'C'

Published in: Education
  • Be the first to comment

Mesics lecture files in 'c'

  1. 1. www.eshikshak.co.in
  2. 2.  A collection of data or information that has a are stored on computer known as file A file is collection of bytes stored on a secondary storage device. There are different types of file  Data files  Text files  Program files  Directory files Different types of file stored different types of information
  3. 3. A file has a beginning and an end, it has a current position, typically defined as on many bytes from the beginning. You can move the current position to any other point in file. A new current position can be specified as an offset from the beginning the file.
  4. 4. A stream is an abstract representation of any external source or destination for data, so the keyword, the command line on your display and files on disk are all examples of stream. ‘C’ provides numbers of function for reading and writing to or from the streams on any external devices.
  5. 5. A stream is a series of bytes data flow from your program to a file or vice-versa. There are two formats of streams which are as follows  Text Stream ▪ It consists of sequence of characters, depending on the compilers ▪ Each character line in a text stream may be terminated by a newline character. ▪ Text streams are used for textual data, which has a consistent appearance from one environment to another or from one machine to another
  6. 6. A stream is a series of bytes data flow from your program to a file or vice-versa. There are two formats of streams which are as follows  Binary Stream ▪ It is a series of bytes. ▪ Binary streams are primarily used for non-textual data, which is required to keep exact contents of the file.
  7. 7. A text file can be a stream of characters that a computer can process sequentially. It is processed only in forward direction. It is opened for one kind of operation (reading, writing, or appending) at any give time. It can read only one character at a time.
  8. 8.  A binary file is collection of bytes. In ‘C’ both a both a byte and a character are equivalent. A binary file is also referred to as a character stream, but there are two essential differences.
  9. 9.  A file is identified by its name. This name is divided into two parts  File Name ▪ It consists of alphabets and digits. ▪ Special characters are also supported, but it depends on operating system.  Extension ▪ It describe the file type
  10. 10.  Before opening a file, we have to create a file pointer. FILE structure is defined in the “stdio.h” header file. It stores the complete information about file.  Name of file, mode it is opened in, starting buffer address, a character pointer that points to the character being read.
  11. 11.  To perform any operation (read or write) the file has to be brought into memory from the storage device. Thus, bringing the copy of file from disk to memory is called opening the file.
  12. 12. Mode Meaningr  Open a text file for reading only. If the file doesn’t exist, it returns null.w  Opens a file for writing only.  If file exists, than all the contents of that file are destroyed and new fresh blank file is copied on the disk and memory with same name  If file dosen’t exists, a new blank file is created and opened for writing.  Returns NULL if it is unable to open the filea  Appends to the existing text file  Adds data at the end of the file.  If file doesn’t exists then a new file is created.  Returns NULL if it is unable to open the file.rb  Open a binary file for readingwb  Open a binary file for readingab  Append to a binary filer+  Open a text file for read/writew+  Opens the existing text file or Creates a text file for read/write
  13. 13. Mode Meaninga+  Append or create a text file for read/writer+b  Open a binary file for read/writew+b  Create a binary file for read/writea+b  Append a binary file for read/write
  14. 14.  fopen() function, like all the file-system functions, uses the head file stdio.h The name of the file to open is pointed to by fname The string pointed at for mode determined how the file may be accessed.
  15. 15. FILE *fp;if(fp = fopen(“myfile”,”r”)) == NULL){ printf(“Error opening a file”); exit(1);}
  16. 16.  When we want to read contents from existing file, then we require to open that file into read mode that means “r” mode To read file follow the below steps 1. Initialize the file variable 2. Open a file in read mode 3. Accept information from file 4. Write it into the output devices 5. Repeat steps 3 and 4 till file is not ends 6. Stop procedure
  17. 17. #include<stdio.h>void main(){ FILE *fp; char ch; fp=fopen(“clear.c”,”r”); if(fp==NULL) print(“Unable to open clear.c”); else { do { ch = getc(fp); putchar(ch); }while(ch!=EOF); fclose(fp); }}
  18. 18.  A file contains a large amount of data. We some times cannot detect the end of file. Intext file, a special character EOP denotes the end-of-file
  19. 19.  To close a file and dis-associate it with a stream, use fclose() function. It returns 0 if successful else returns EOP if error occurs. The fcloseall() closes all the files opened previously.
  20. 20. #include<stdio.h>void main(){ FILE *fp; char ch; fp=fopen(“clear.c”,”r”); if(fp==NULL) print(“Unable to open clear.c”); else { do { ch = getc(fp);// gets the character from file putchar(ch); }while(ch!=EOF); fclose(fp); }}
  21. 21.  We can add contents to the existing file whenever it is required. Perform the following steps 1. Initialize the variable 2. Open a file in append mode 3. Accept information from user 4. Write it into the file 5. Repeat steps 3 and 4 according to user’s choice 6. Stop procedure
  22. 22.  char *fgets(char *str, int n, FILE *fptr);  This statement reads character from the stream fptr into to the character array ‘str’ until a new line character is read or end of file is reached or n-1 characters have been read. fputs(const char *str, FILE *fptr);  This statement writes to the stream fptr except the terminating null character of string ‘str’
  23. 23. #include<stdio.h>void main(){ FILE *fp; char line[280];int ch, i=0; fp=fopen(“a.dat”,”a”); if(fp==NULL) print(“Unable to open clear.c”); else { do{ do{ line[i++] = getchar(); }while(line[i-1]!=‘*’); fputs(line, fp);//Writes string to the file i=0; printf(“nPress 1 to continue”); scanf(“%d”,&ch); }while(ch==1); fclose(fp); printf(“File is successfully created”); }}
  24. 24.  We can modify the files in two ways  Serial access  Random access Generally all the text files are considered to be sequential files because lines of text files or records of the formatted files are not equal. So address of each record is un predictable Whereas, in random access file all the record length are same.
  25. 25.  To modify the file open the file with read and write mode “r+” or “w+” or “a+” Generally “r+” mode is use for this purpose 1. Initialize the variable 2. Open a file in read/write mode 3. Read information from file 4. Print it 5. Check whether the information is right or wrong? 1. If Wrong, accep correct information from user, move the file pointer to the start of record or information. Re-write it that means new information into the file. 2. If not wrong, go to step 6. 6. Repeat steps 3 to 6 till file is not end. 7. Stop procedure
  26. 26.  To modify the file open the file with read and write mode “r+” or “w+” or “a+” Generally “r+” mode is use for this purpose 1. Initialize the variable 2. Open a file in read/write mode 3. Read information from file 4. Print it 5. Check whether the information is right or wrong? 1. If Wrong, accep correct information from user, move the file pointer to the start of record or information. Re-write it that means new information into the file. 2. If not wrong, go to step 6. 6. Repeat steps 3 to 6 till file is not end. 7. Stop procedure
  27. 27. #include<stdio.h>struct stock{ int itid, qty; char n[100]; float rate;}it;void main(){ FILE *fp; int ch; int r = 0; fp = fopen(“item.c”, “r+”); if(fp==NULL) { printf(“Unable to open item.c”); }}
  28. 28. else{ do{ fread(&it, sizeof(it),1,fp); printf(“n%d %s %d %f”, it.itid, it.n, it.qty, it.rate); printf(“n Press 1 to change it?”); scanf(“%d”,&ch); if(ch==1) { printf(“n Enter Itemid ItemName Quantity & Price”); scanf(“%d%s%d%f”, &it.itid, it.n, &it.qty, &it.rate); fseek(fp, r*sizeof(it), 0); fwrite(&it, sizeof(it),1,fp); }r++; }while(!feof(fp)); fclose(fp);}}
  29. 29. fseek(FILE *fptr, long offset, int reference) Moves the pointer from one record to another. The first argument is the file pointer The second argument tells the compiler by how many bytes the pointer should be moved from a particular position. The third argument is the reference from which the pointer should be offset.
  30. 30. fseek(FILE *fptr, long offset, int reference) The third argument is the reference from which the pointer should be offset.  SEEK_END moves the pointer from end of file  SEEK_CUR moves the pointer from the current position  SEEK_SET moves the pointer from the beginning of the file
  31. 31. fseek(FILE *fptr, long offset, int reference) Example  fseek(fptr, size, SEEK_CUR) sets the cursor ahead from current position by size bytes  fseek(fptr, -size, SEEK_CUR) sets the cursor back from current position by size bytes  fseek(fptr, 0, SEEK_END) sets cursor to the end of the file  fseek(fptr, 0, SEEK_SET) sets cursor to the beginning of the file

×