A structured lesson workspace with readable content, hands-on examples, and a clean path to completion.
truncate sets a file to a specified length. If the new length is shorter, data beyond that point is discarded. If longer, the file is extended with zero bytes. The POSIX version in unistd.h operates on a path. ftruncate operates on a file descriptor. Neither requires you to open the file with fopen. This is a system call wrapper, not a standard C library function, so it is not available on Windows without POSIX compatibility layers.
#include <stdio.h>#include <unistd.h>#include <sys/stat.h>int main(void) {FILE *fp = fopen("trunc_test.txt", "w");fputs("This is a long line of text that will be shortened.\n", fp);fclose(fp);struct stat st;stat("trunc_test.txt", &st);printf("Before: %ld bytes\n", (long)st.st_size);if (truncate("trunc_test.txt", 10) != 0) {perror("truncate");return 1;}stat("trunc_test.txt", &st);printf("After: %ld bytes\n", (long)st.st_size);fp = fopen("trunc_test.txt", "r");char buf[64];size_t n = fread(buf, 1, sizeof(buf) - 1, fp);buf[n] = '\0';printf("Content: '%s'\n", buf);fclose(fp);return 0;}
The file went from 53 bytes to 10. Everything after byte 10 is gone. The content is now "This is a " with no newline. If you truncate to a length larger than the current file size, the gap is filled with null bytes (\0). This is how sparse files are created on filesystems that support them.
ftruncate takes a file descriptor (from open, not fopen) and a length. Use it when you already have the file open and want to resize without closing and reopening. The fileno function extracts the file descriptor from a FILE pointer if you need to bridge the two APIs.
#include <stdio.h>#include <unistd.h>int main(void) {FILE *fp = fopen("trunc_test.txt", "r+");if (fp == NULL) {perror("fopen");return 1;}int fd = fileno(fp);if (ftruncate(fd, 5) != 0) {perror("ftruncate");fclose(fp);return 1;}printf("Truncated to 5 bytes via ftruncate.\n");fclose(fp);return 0;}
truncate and ftruncate are POSIX tools for file size management. They appear in database engines, log rotators, and file format writers. On Windows, the equivalent is SetEndOfFile via the Win32 API. Next module: recursion, where functions call themselves and the stack becomes both your tool and your enemy.
Finish the lesson once you have worked through the material. This awards ★ 20 XP.