CS_8251 - Unit 5 - Files
About File Processing using C function calls
60 flashcards · Programming Languages · by kgashok
FILE is typedef forstruct _iobuf
How do you declare/define something as a new type in C?
FILE It's not a keyword, it's a data type defined in the ANSI C standard to operate with files. It usually points to an internal structure that describes the file and its current state to the library functions.
What is the typedef again?
int *a, b; Which is correct? A. a is a pointer to int, and b is a pointer to int B. a is a pointer to int, b is an int C. Compile error D. Undefined behaviour
Choice B This is the reason why we choose the recommended convention T *a; int *a, b;
int* a, b; Which is correct? A. a is a pointer to int, and b is a pointer to int C. Compile error D. Undefined behaviour E. None of the above
Choice E a is a pointer to int b is an int If the objective was to define two pointers, use the recommended convention int *a, *b; or when in doubt, use int *a; int *b;
FILE* fp; // code_A FILE *fp; // code_B FILE * fp; // code_C code_A, code_B and code_C are not the same. True or False? code_A is preferable. Yes or No?
False - All are the same. No - code_B is preferred. T *a; is the preferred C style for declaring a pointer to T as used in Kernighan & Ritchie's book about C and the ISO standard as well. When declaring / defining pointer variables, the asterisk should go with the variable identifier, not the type name. That is the preferred convention.
A binary file is a collection of bytes.
both start with letter 'b'
A text file is a stream of characters that can be processed sequentially.
It is in ASCII
In sequential access, the position indicator gets automatically adjusted.
Automatically or manually?
In random access, reading/writing is done from/to any position by manually controlling the position indicator.
Automatically or manually?
A record consists of collection of data fields that conform to a previously defined structure that can be stored on or retrieved from a file.
It is one of the two basic components (the other one being field) of a database.
FILE*fp; fp=fopen("one.txt", "r"); If one.txt file exists, fp will point to a valid FILE object. True or False?
True.
FILE *fp = fopen(const char *filename, const char *mode); Here filename is the name of the file to be opened and mode specifies the purpose of opening the file. fp is the FILE pointer which will hold the reference to the opened (or created) file.
Clues: Use among the three below reference, purpose, name
#include <stdio.h> #include <conio.h> main() { FILE *fp; char ch; // open a text file for writing into it fp = fopen ("one.txt","w"); printf("Enter data"); while( (ch = getchar()) != EOF) { putc(ch, fp); } fclose(fp); // open a text file for reading from it fp = fopen("one.txt", "r"); while( (ch = getc(fp)) != EOF) printf("%c", ch); fclose(fp); }
What is the access mode (letter within quotes) for writing? What is the access mode (letter within quotes) for reading?
Open a file in write mode ("w") creates a file if a file is not present If the file is present, it then overwrites the original contents of the file. True or False?
True
Open a file in append mode ( "a" ) creates a file if a file is not present If the file is present, it then adds (or appends) to the original contents of the file. The cursor is positioned at the end of the present data in the file.
read, write and...then what is the third mode?
You have been asked to code up a program to update the contents of an existing file. You prompt the user with the following question: "Do you want to overwrite the existing information in the file? (Yes / No)" If the user responds with "Yes", you will open the file (to be modified) using the write mode. If the user responds with "No", you will use the append mode.
Choose between "read", "write" and "append"
Snippet A // fp is a valid reference to a file // token is a valid character array variable fscanf(fp, "%s", token); Snippet A is used for reading from a text file. True or False? Snippet B // fp is a valid reference to a file // token is a valid integer variable fread(&token, sizeof(token), 1, fp); Snippet B is used for reading from a binary file. True or False?
True True Snippet A is for reading a string from a text file. Snippet B is for reading an integer from a binary file.
Snippet A // fp is a valid reference to a file // token is a valid integer variable fwrite(&token, sizeof(token), 1, fp); Snippet A is used for writing to a text file. True or False? Snippet B // fp is a valid reference to a file // token is a valid character array variable fprintf(fp, "%s", token); Snippet B is used for writing to a binary file. True or False?
False False Snippet A is for writing to a binary file. Snippet B is for writing to a text file.
What is the advantage of text files over binary files?
PORTABILITY Due to differences in binary data representations across platforms, files written in binary format often are not portable. For more portable file representations, consider using text files.
What is the advantage of binary files over text files?
SPEED and EFFICIENCY One of the advantages of binary files is that they are more efficient. In terms of memory, storing values using numeric formats such as IEEE 754, rather than as text characters, tends to use less memory. In addition, binary formats also offer advantages in terms of speed of access.
A file is a collection of bytes stored on a secondary storage device, which is generally a disk of some kind. It is identified by a name, which is given at the time of its creation. It may be amended, moved from one storage device to another or removed completely when desired.
An I/O asset of the operating system.
The C language provides three standard streams that are always available to a C program. These are Name Description Example stdin -> Standard Input Keyboard stdout -> Standard Output Screen stderr -> Standard Error Screen They are all of the same type: FILE *
Along with files, this helps in the input/output operations of a program.
int main(int argc, char *argv[]) { if (argc == 2) { qsort(argv[1], strlen(argv[1]), sizeof(char), comparator_char); printf("%s\n", argv[1]); } else if (argc > 2) { qsort(&argv[1], argc - 1, sizeof(char *), comparator); while (argc > 1) printf("%s\n", argv[--argc]); } else { puts("No args to sort!"); } return 0; } The compiled version of the above program is available as main The output of main zxydcba -> A. zxydcba B. Segmentation error C. abcdxyz D. None of the above
Choice C This program is a good example of how a C program interacts with command line arguments through the variables int argc and char* argv[] when only 2 arguments (i.e. argc == 2) are available in the program invocation, the 2nd argument's letters are sorted and printed out.
int main(int argc, char *argv[]) { if (argc == 2) { qsort(argv[1], strlen(argv[1]), sizeof(char), comparator_char); printf("%s\n", argv[1]); } else if (argc > 2) { qsort(&argv[1], argc - 1, sizeof(char *), comparator); while (argc > 1) printf("%s\n", argv[--argc]); } else { puts("No args to sort!"); } return 0; } The compiled version of the above program is available as main The output of main zebra monkey abel -> A. zebra monkey abel B. Segmentation error C. abel monkey zebra D. None of the ab…
Choice C This program is a good example of how a C program interacts with command line arguments through the variables int argc and char* argv[] when there are more than 2 arguments (i.e. argc > 2) are available, all the strings pointed to by the argv array pointers are sorted and printed.
fseek() - It is used to move the reading control to different positions in the file. ftell() - It tells the byte location of current position of cursor in file pointer. rewind() - It moves the control to beginning of the file.
What are the functions required to control the file_position_indicator? They are required to perform random access of data in a file.
sizeof(Client) == sizeof(struct_client) ? True or False sizeof(Client) == 38? True or False sizeof(struct client) == 40? True or False sizeof(client.balance) == 4? True or False
True False True True Although account_id (4) + name(30) + balance(4) == 38, the compiler allots 40 bytes to each structure for sake of efficiency of retrieval.
You need to read and make updates to the file contents in file clients.txt. Will the above code work? If not, what changes will you make?
FILE *fp = fopen("clients.txt", "r+"); Mode must be either "r+" or "w+".
int res = fread(&entries, sizeof(Client), 100, fp); Which of the following is true? A. If `fp` is valid reference to a file, the code will execute B. If there 100 entries of sizeof(Client) in the file, the value of res will be 100. C. If there are only 4 entries in the file, the value of res will be -1 D. None of the above
A and B are true. C is not true. res will have a value that is equal to the number of Client entries that were present in the file. If the file had 4 Client entries, then res will have the value 4.
You need to update the 2nd client entry from the last in a file. The size of each entry is sizeof(struct client) What code will you write to move the file cursor to the correct position? A. fseek(fp, -2, SEEK_END) B. fseek(fp, -2, SEEK_SET) C. fseek(fp, 2*sizeof(struct client), SEEK_END) D. fseek(fp, -2*sizeof(struct client), SEEK_CUR) E. fseek(fp, -2*sizeof(struct client), SEEK_END)
Choice E int fseek( FILE *stream, long int offset, int whence ); The function prototype for fseek is where offset is the number of bytes to seek from whence in the file pointed to by stream — a positive offset seeks forward and a negative one seeks backward. Argument whence is one of the values SEEK_SET, SEEK_CUR or SEEK_END which indicate the location from which the seek begins. SEEK_SET - the seek starts at the beginning of the file SEEK_CUR - the seek starts at the current location in the fi…
int fseek (FILE *stream, long int offset, int whence); The function prototype for fseek is where the offset is the number of bytes to seek from whence in the file pointed to by stream — a positive offset seeks forward and a negative one seeks backward. Argument whence is one of the values SEEK_SET, SEEK_CUR or SEEK_END which indicates the location from which the seek begins. SEEK_SET - the seek starts at the beginning of the file SEEK_CUR - the seek starts at the current location in the file an…
whence meaning: from which; from where. whence: from what place or source.
Client update; fread(&update, sizeof(update), 1, fp); printf("%u %s %d\n", update.account_id, update.name, update.balance); After the above code executes, it produces the output 2 junkie -100 What code will you write to update the balance value to 10000? update.balance = 10000
Review of structure fundamentals
Attempt the Random Access challenge available at http://j.mp/fileUpdateC Make the correct changes to the code as indicated. What are the last 5 lines of the output?
Validating update - 0 ashok 90 - 1 bala 100 - 2 junkie -10000 - 3 mala 11
What are the four changes you will make to the below code to make the update to a specific record work?
Assume that array clist is of size i, where i<100i < 100i<100 . The goal is to write all the entries in array clist to a file. A. Only Option A code is valid. B. Only Option A, B are both valid. C. Files clients.txt, clients2.txt and clients3.txt will all be of the same size and have the same contents.
A. False. B. False. C .True.
There are two types of files. What are they?
Text files and binary files.
To process files, there are two types of access possible. What are they?
Sequential access and Random access.
Sequential Write to File To write text files which can be read sequentially later on, what functions do you have to use? fprintf
The equivalent of printf to write to console, this is to file...
Sequential Read from File To read text files sequentially, what two functions do you have to use in combination? sscanf and fgets
ONE of them: The equivalent of scanf to read from console, this is equivalent of scanning from a text buffer. NB: The other option to sequential read from text file is fscanf
The entries array contains valid data. The goal is to create a text file. Each clients has to incremented with Rs 100. There are 4 steps required to modify the current code (below) to transfer the contents to a sequential file (clients2.txt) and read it back. What are the code snippets for each of the steps?
Attempt the Sequential Access challenge available at http://j.mp/fileUpdate2C Make the correct changes to the code as indicated. What are the last 5 lines of the output?
Reading contents of clients2.txt - 0 ashok 190 - 1 bala 200 - 2 junkie 0 - 3 mala 111
Function Description fopen() create a new file or open a existing file fclose() closes a file fflush() writes out buffer contents to file SEQUENTIAL OPERATIONS getc() reads a character from a file getw() reads a integer from a file fscanf() reads a set of data from a file putc() writes a character to a file putw() writes a integer to a file fprintf() writes a set of data to a file fgets() gets a string from a file of specified length BINARY OPERATIONS fseek() set the position to desired point f…
All important functions related to file processing.
Text Mode Description r Open an existing file for reading. r+ Open an existing file for update (reading and writing). w Create a file for writing. If the file already exists, discard the current contents. w+ Create a file for update. If the file already exists, discard the current contents. a, a+ Append: open or create a file for writing at the end of the file. Binary Mode Description rb opens a binary file in reading mode wb opens or create a binary file in writing mode ab, ab+ opens a binary…
All possible modes in which files can be opened.
Command Line arguments are available to a C program through the two variables argc (of type int) and argv(of type char**)
These are the parameters of the main function.
argv[0] is inevitably the name of the executable file that was invoked.
Alternative name for main or main.exe?
A record consist of a collection of data fields that conforms to a previously defined structure that can be stored on or retrieved from a file.
In random access, compound retrieval of data is attributed to this.
You have been asked to write a spell checker program to correct the spelling mistakes in a text file. To be efficient, which of the two processing methods will you use? A Sequential access (for reading only) B Sequential access (for both reading and writing) C Random access (for both reading and writing ) D Random access for reading and Sequential access for writing
Choice B
You have been asked to write a client accounts management program for a bank that will make updates to specific accounts several number of times in the course of the day. To be efficient, which of the two processing methods will you use? A Sequential access (for reading only) B Sequential access (for both reading and writing) C Random access (for both reading and writing ) D Random access for reading and Sequential access for writing
Choice C
Assume c is character variable, Assume inFilePtr is a valid reference to a file (to read from), Assume outFilePtr is a valid reference to a file (to write to), while ((c = fgetc(inFilePtr)) != EOF) { fputc(c, outFilePtr); } The above code snippet will cause All contents from inFilePtr to be copied to outFilePtr All contents in inFilePtr to be deleted and put in outFilePtr All contents in outFilePtr to be deleted and put in inFilePtr None of the above
Choice 1
The tmpfile() function is used to create a temporary file. The function opens the corresponding stream with access parameters set as “w+”. The file created with the said function will be automatically deleted when all references to the file are closed. That is, the file created will be automatically closed and erased when the program has been completely executed.
Try it out on https://repl.it/@ashokb/tempFileCreation
Client update; fread(&update, sizeof(update), 1, fp); After the above code, other statements made some updates to update's elements. What code will write these changes back to the file (referenced by fp) at the same location from which it was read? A. fwrite(update, sizeof(update), 1, fp); B. fseek(fp, sizeof(update), SEEK_END); C. fseek(fp, -sizeof(update), SEEK_CUR); fwrite(update, sizeof(update), 1, fp); D. None of the above
Choice C
Write the code (Line 20-23) that will complete the below namesake function. The function returns the number of the first line at which two files differ from each other.
if(strcmp(line1, line2) != 0) { diff = 1; break; } strcmp will either be greater than zero or lesser than zero if the two lines from the two files are different from each other. When that condition is satisfied, we set the flag diff, and break out of the loop. Visit https://repl.it/@ashokb/compareTwoFiles and try it out youself. NOTE: File 1 and File 3 are different in the 3rd line.
Write a program to display the name of the executable that was used to launch/run the program.
int main (int argc, char *argv[]) { printf("%s\n", argv[0]); return 0; }
When the funciton fopen() attempts to open a non-existent file, it returns NULL.
If the file is available, fopen() returns a valid reference to the same file. Otherwise, what does it do?
Function feof() (file pointer at end-of-file marker aka EOF?) returns a true (nonzero) value only after the program attempts to read the nonexistent data following the last line.
// until there is valid data in the file if (!feof(fp)) { // ... // }
rewind( cfPtr ); causes a program’s file position pointer—which indicates the number of the next byte in the file to be read or written—to be repositioned to the beginning of the file, i.e. byte 0 .
What is the value of number that represents the 1st byte in the file?
Random-access files are appropriate for airline reservation systems banking systems point-of-sale systems any kinds of transaction-processing systems that require rapid access to specific data.
Opposite of "sluggish" or "slow"
What are the various operations when it comes to file management?
File management: It basically means all operations related to creating, renaming, deleting, merging, reading, writing, etc. of any type of files.
argv [0] is the name of the program invoked. argv [1] is a pointer to the first argument supplied. argv [argc-1] is a pointer to the last argument supplied. If no arguments are supplied, argc will be 1. For n arguments, argc will be equal to n+1.
Do you really know your argc and argv parameters of the main function in a C program?
int filecopy(FILE* source, FILE* dest) { int count = 0; char c; if (source != 0 && dest != 0) { while ((c = fgetc(source)) && !feof(source) && ++count) fputc(c, dest); rewind(source); rewind(dest); return count; } return -1; } Assume source and dest are valid reference. Will the above function work? If yes, what will it return?
Yes. It will return the number of bytes copied from source to dest.
int file_copy(FILE* source, FILE* dest); int file_append(FILE* source, FILE* dest) { int res = fseek(dest, 0, SEEK_END); int count = 0; if (!res) { count = file_copy(source, dest); return count; } return -1; } Assume that the file_copy function works as expected. What is the change you will make to file_append to make it work properly?
file_append attempts to copy the contents in the source file at the end of dest file. which random access file function to use? what is the whence value you have to use?