Consider the following C code that writes and reads from a file using file pointers. What will be printed on the screen?
#include <stdio.h> int main() { FILE *fp = fopen("test.txt", "w+"); fputs("Hello, world!", fp); fseek(fp, 7, SEEK_SET); char buffer[6]; fgets(buffer, 6, fp); printf("%s\n", buffer); fclose(fp); return 0; }
Remember that fgets reads up to n-1 characters and adds a null terminator.
The code writes "Hello, world!" to the file, then moves the file pointer to position 7 (the 'w' in "world!"). fgets(buffer, 6, fp) reads 5 characters plus the null terminator. So it reads "world" (5 chars) and stops before the '!'.
Given this code snippet, what will be the output?
#include <stdio.h> int main() { FILE *fp = fopen("data.txt", "r"); if (!fp) { printf("File not found\n"); return 1; } fseek(fp, 0, SEEK_END); long size = ftell(fp); printf("%ld\n", size); fclose(fp); return 0; }
Think about what ftell returns after seeking to the end of the file.
The code opens the file in read mode, moves the file pointer to the end using fseek, then uses ftell to get the current position, which equals the file size in bytes.
Examine the code below. It attempts to read a line from a file. Why does it cause a runtime error?
#include <stdio.h> int main() { FILE *fp = fopen("input.txt", "r"); char *line; if (fp == NULL) { return 1; } fgets(line, 100, fp); printf("%s", line); fclose(fp); return 0; }
Think about where line points before calling fgets.
The variable line is a pointer but it is not initialized to point to valid memory. Using fgets to write into it causes undefined behavior and usually a runtime crash.
Which of the following code snippets will cause a compilation error related to file pointers?
Remember how FILE and FILE * types are used.
Option C declares fp as a FILE struct, but fopen returns a pointer to FILE. Assigning a pointer to a struct variable causes a compilation error.
Given the file "example.txt" contains the text "ABCDE\nFGHIJ", how many characters will be printed by this program?
#include <stdio.h> #include <string.h> int main() { FILE *fp = fopen("example.txt", "r"); char buffer[5]; int count = 0; while (fgets(buffer, sizeof(buffer), fp)) { printf("%s", buffer); count += strlen(buffer); } fclose(fp); printf("\nTotal chars: %d\n", count); return 0; }
Remember that fgets reads up to n-1 characters and includes the newline if present.
The file has 11 characters including the newline. The code reads in chunks of 4 characters plus null terminator. It reads "ABCD", then "E\nFG", then "HIJ". The total characters printed and counted are 11.