Complete the code to open a file named "data.txt" for reading.
#include <stdio.h> int main() { FILE *fp; fp = fopen("data.txt", "[1]"); if (fp == NULL) { printf("Failed to open file.\n"); return 1; } fclose(fp); return 0; }
The mode "r" opens the file for reading. Other modes like "w" are for writing, "a" for appending.
Complete the code to write the string "Hello" to the file using fprintf.
#include <stdio.h> int main() { FILE *fp = fopen("output.txt", "w"); if (fp == NULL) { return 1; } fprintf(fp, "[1]\n"); fclose(fp); return 0; }
"Hello" is the string to write to the file as per the instruction.
Fix the error in the code to correctly read a line from the file into buffer.
#include <stdio.h> int main() { char buffer[100]; FILE *fp = fopen("input.txt", "r"); if (fp == NULL) { return 1; } fgets([1], 100, fp); printf("%s", buffer); fclose(fp); return 0; }
fgets expects a pointer to a char array, so passing "buffer" is correct.
Fill both blanks to create a dictionary of word lengths for words longer than 3 characters.
#include <stdio.h> #include <string.h> int main() { char *words[] = {"cat", "elephant", "dog", "giraffe"}; int lengths[4]; int count = 0; for (int i = 0; i < 4; i++) { if (strlen(words[i]) [1] 3) { lengths[count] = strlen(words[i]); count[2]; } } for (int j = 0; j < count; j++) { printf("%d\n", lengths[j]); } return 0; }
The condition checks if word length is greater than 3, and count is incremented with ++.
Fill all three blanks to create a file pointer, open a file for appending, and write a line.
#include <stdio.h> int main() { FILE *[1]; [1] = fopen("log.txt", "[2]"); if ([1] == NULL) { return 1; } fprintf([1], "Log entry\n"); fclose([1]); return 0; }
Use variable name "fp" for the file pointer, open file in append mode "a", and use "fp" to write and close.