From b826126635dc1a01d93a8c461fc4c56b1163ac30 Mon Sep 17 00:00:00 2001 From: Robert Preston Date: Thu, 2 Jul 2026 09:34:19 +1000 Subject: [PATCH] program lines - read lines from a text file using fgets --- c_programming/files/files.txt | 8 ++++++++ c_programming/files/lines.c | 37 +++++++++++++++++++++++++++++++++++ c_programming/files/lines.txt | 4 ++++ 3 files changed, 49 insertions(+) create mode 100644 c_programming/files/files.txt create mode 100644 c_programming/files/lines.c create mode 100644 c_programming/files/lines.txt diff --git a/c_programming/files/files.txt b/c_programming/files/files.txt new file mode 100644 index 0000000..00d615f --- /dev/null +++ b/c_programming/files/files.txt @@ -0,0 +1,8 @@ +Reading and Writing Files in C + +copy - copy one file to a new file, one letter at a time. + +lines - read lines from a text file using fgets. +todo: lines_2 - remove the \n from the end of each line. +https://stackoverflow.com/questions/2693776/removing-trailing-newline-character-from-fgets-input +https://man.freebsd.org/cgi/man.cgi?query=strcspn&sektion=3 \ No newline at end of file diff --git a/c_programming/files/lines.c b/c_programming/files/lines.c new file mode 100644 index 0000000..9515c75 --- /dev/null +++ b/c_programming/files/lines.c @@ -0,0 +1,37 @@ +// A program that iterates one line at a time. +// uses fgets. +// https://manual.cs50.io/3/fgets + +// read the lines from lines.txt and print them out. + +#include + +// char *fgets(char s[restrict .size], int size, FILE *restrict stream); + +// reads in at most one less than size characters from stream and stores them +// into the buffer pointed to by s. Reading stops after an EOF or a newline. +// If a newline is read, it is stored into the buffer. A terminating null byte +// ('\0') is stored after the last character in the buffer. + +// lines.c is based on the example at https://en.cppreference.com/c/io/fgets + + +#define SIZE 64 + +int main(void) +{ + FILE* infile = fopen("lines.txt", "r"); + char buf[SIZE]; + + while (fgets(buf, sizeof buf, infile) != NULL) + { + printf("%s", buf); + } + + if (feof(infile)) + { + puts("End of file reached"); + } + + return 0; +} \ No newline at end of file diff --git a/c_programming/files/lines.txt b/c_programming/files/lines.txt new file mode 100644 index 0000000..04ad0cd --- /dev/null +++ b/c_programming/files/lines.txt @@ -0,0 +1,4 @@ +Line one +Line two + +Line four \ No newline at end of file