#include <stdio.h> int main() { FILE *fp = fopen("testfile.txt", "w"); if (fp == NULL) return 1; fprintf(fp, "Hello, world!\n"); fclose(fp); return 0; }
Opening a file in "w" mode creates the file if it does not exist or truncates it to zero length if it does. Then, writing to the file adds the given content. So the file will contain exactly the string written.
#include <stdio.h> int main() { FILE *fp = fopen("nofile.txt", "r"); if (fp == NULL) { printf("File not found\n"); } else { printf("File opened\n"); fclose(fp); } return 0; }
When opening a file in "r" mode, if the file does not exist, fopen returns NULL. So the program prints "File not found".
#include <stdio.h> int main() { FILE *fp = fopen("append.txt", "a"); if (fp == NULL) return 1; fprintf(fp, "Line2\n"); fclose(fp); return 0; }
Opening a file in "a" mode moves the write position to the end of the file. Writing adds new content after existing data. So the file will have the original content plus the new line appended.
#include <stdio.h> int main() { FILE *fp = fopen("data.txt", "r+"); if (fp == NULL) { perror("Error opening file"); return 1; } fclose(fp); return 0; }
Opening a file in "r+" mode requires the file to exist. If it does not, fopen returns NULL and perror prints the error message about missing file.
#include <stdio.h> int main() { FILE *fp = fopen("example.txt", "w+"); if (fp == NULL) return 1; fprintf(fp, "NewContent\n"); fseek(fp, 0, SEEK_SET); char buffer[20]; fgets(buffer, sizeof(buffer), fp); printf("Read from file: %s", buffer); fclose(fp); return 0; }
Opening a file with "w+" truncates it to zero length. Writing "NewContent\n" adds data, but the output buffer is not flushed before reading. The fseek resets the position, but the buffer may not be flushed, so fgets reads empty content. The printed line is empty after "Read from file:".