83 lines
2.3 KiB
Plaintext
Raw Normal View History

2025-11-23 13:53:36 +01:00
int main() {
printf("=== File I/O Tests ===\n");
printf("Test 1: Writing to a file\n");
int f = fopen("test_output.txt", "w");
if (f == 0) {
printf("ERROR: Could not open file for writing\n");
return 1;
}
fputs(f, "Hello, File I/O!\n");
fputs(f, "This is line 2.\n");
fputs(f, "Testing file operations.\n");
fclose(f);
printf("PASS: File written successfully\n");
printf("Test 2: Reading from file using fgets\n");
f = fopen("test_output.txt", "r");
if (f == 0) {
printf("ERROR: Could not open file for reading\n");
return 1;
}
char *line1 = fgets(f, 256);
printf("Line 1: %s", line1);
char *line2 = fgets(f, 256);
printf("Line 2: %s", line2);
char *line3 = fgets(f, 256);
printf("Line 3: %s", line3);
fclose(f);
printf("PASS: File read successfully\n");
printf("Test 3: File position operations\n");
f = fopen("test_output.txt", "r");
if (f == 0) {
printf("ERROR: Could not open file\n");
return 1;
}
int pos = ftell(f);
printf("Initial position: %d\n", pos);
fseek(f, 7, SEEK_SET());
pos = ftell(f);
printf("Position after seek: %d\n", pos);
char *partial = fgets(f, 256);
printf("Read after seek: %s", partial);
fclose(f);
printf("PASS: File positioning works\n");
printf("Test 4: End of file detection\n");
f = fopen("test_output.txt", "r");
if (f == 0) {
printf("ERROR: Could not open file\n");
return 1;
}
int line_count = 0;
while (feof(f) == 0) {
char *line = fgets(f, 256);
if (strlen(line) > 0) {
line_count = line_count + 1;
}
}
printf("Total lines read: %d\n", line_count);
fclose(f);
printf("PASS: EOF detection works\n");
printf("Test 5: File rename operation\n");
int result = frename("test_output.txt", "test_renamed.txt");
if (result == 0) {
printf("PASS: File renamed successfully\n");
} else {
printf("ERROR: File rename failed\n");
}
printf("Test 6: File removal\n");
result = fremove("test_renamed.txt");
if (result == 0) {
printf("PASS: File removed successfully\n");
} else {
printf("ERROR: File removal failed\n");
}
printf("\n=== All File I/O Tests Completed ===\n");
return 0;
}