Files Flashcards
(21 cards)
Why do we use files in C programming?
For permanent storage of data, to read and process large amounts of data, and to save program output permanently.
What is a FILE pointer and how is it declared?
A special pointer that keeps track of the current position within a file. Declared as FILE *fp;.
List three file opening modes and their purpose.
“r”: Read mode (file must exist).
“w”: Write mode (creates new file or overwrites existing).
“a”: Append mode (creates new file or adds to end of existing).
“r+”: Read and write (file must exist).
“w+”: Read and write (creates/overwrites).
“a+”: Read and append.
What is the difference between fprintf() and fputs()?
fprintf(): Writes formatted output to a file (like printf).
fputs(): Writes a string to a file.
How do you read a file character by character until the end of the file?
Using a while loop with fgetc() and checking for EOF.
e.g., while ((ch = fgetc(fp)) != EOF) { … }
What is the purpose of fseek() and ftell()?
fseek(): Repositions the file pointer to a specific location within the file.
ftell(): Returns the current position of the file pointer.
How do you close the file associated with the file pointer fp?
fclose(fp);
How do you write the string “Hello File!” to a file using fprintf() and fputs() with a file pointer fp?
fprintf(fp, “Hello File!\n”);
fputs(“Hello File!\n”, fp);
How do you read a single character from a file pointed to by fp into ch, and what value indicates the end of the file?
char ch = fgetc(fp); The end of the file is indicated by EOF.
How do you read an entire line from a file pointed to by fp into a character array line (max 100 characters)?
fgets(line, 100, fp);
How do you move the file pointer fp to the beginning of the file using fseek()?
fseek(fp, 0, SEEK_SET);
Format of fseek function
int fseek(file pointer, offset, reference point)
SEEK_SET - Beginning of file
SEEK_CUR - Current position of the file pointer
SEEK_END - End of file
Text file vs binary file
Text file can be opened in a simple editor such as notepad.
Binary file cannot be opened without a specific application software. For example EXE file, JPG, MP3, PDF etc.
Syntax of opening file
FILE *fp = fopen(“example.txt”, “w”);
if (fp == NULL) {
printf(“File cannot be opened.\n”);
} else {
printf(“File opened successfully.\n”);
}
close file syntax
fclose(fp);
printing number to file syntax
fprintf(fp, “The number is %d\n”, num);
write a single character
fputc(‘A’, fp);
fputc(‘\n’, fp);
write a string
fputs(“Hello, World!”, fp);
Using fscanf() – formatted input (like scanf)
fscanf(fp, “The number is %d”, &x);
Using fgetc() – read one character at a time
FILE *fp = fopen(“char.txt”, “r”);
char ch = fgetc(fp);
printf(“Character: %c\n”, ch);
fclose(fp);
Using fgets() – read string (line by line)
FILE *fp = fopen(“string.txt”, “r”);
char line[100];
fgets(line, sizeof(line), fp);
printf(“Line: %s\n”, line);
fclose(fp);