File IO Flashcards
What are the functions that can be used to
- read from stdin
- output to the stdout
Single character at a time?
int getchar(void): can be used to read in a single character at a time from the stdin
int putchar(int c) can be used to output a single character at a time.
What does getchar return?
getchar returns an EOF or an unsigned char
What is the prototype for fopen and what does it return?
the prototype for fopen is
FILE* fopen (const char* fname, const char* mode);
It returns either:
- NULL, if the file doesn’t exist
- the handle/stream to the file.
What are the different modes in which a file can be opened and what are the symbols?
The different modes are:
- r: read
- w: write
- a: append
What is the prototype of fprintf and how does it work?
int fprintf (FILE* fp, char* format, ……);
It takes in a file pointer/handler and then writes the text along with the input data onto that file.
Name the functions that can be used to write a character, and a string to a file.
Character: fputc(char c, FILE* fp);
String: fputs(char* str, FILE* fp);
Name the functions that can be used to read a
- character and also to read
- A string of length n
char c = fgetc(fp);
fgets(s, n, fp);
where n is the maximum length to read, the read string will be stored inside the variable s
gets vs fgets
gets: does not care about the size of the buffer and reads until a newline is found. The newline is not kept by gets.
fgets: reads from the file and stops when the maximum number of bytes are read, a newline character is found or the end of file is reached.
When fgets encounters a newline, it keeps it.
puts vs fputs
puts adds an extra \n after printing
fputs does not