Commit 923eea02 authored by Erik Strand's avatar Erik Strand
Browse files

Read a text file

parent c98c0bdf
......@@ -5,11 +5,14 @@ CXX = g++
CFLAGS = -Wall -O3
.PHONY: all
all: add_integers
all: add_integers read_file
add_integers: add_integers.c
$(CC) $(CFLAGS) -o add_integers add_integers.c
$(CC) $(CFLAGS) -o $@ $<
read_file: read_file.c
$(CC) $(CFLAGS) -o $@ $<
.PHONY: clean
clean:
rm add_integers
rm add_integers read_file
#include <stdio.h>
int main() {
int c;
FILE *file;
// The second argument indicates that we just want to read the file. (We'd put "w" if we wanted
// to write instead.)
file = fopen("test.txt", "r");
// The file might not have opened successfully. For instance if "test.txt" doesn't exist.
if (file) {
// We read characters from the file one at a time, and print them. There are more efficient
// ways to load the data if you want to deal with bigger files, but this gets you pretty
// far, especially compared to scripting languages.
while ((c = getc(file)) != EOF) {
// This is like printf, but for only one character.
putchar(c);
}
fclose(file);
}
}
This text is in a file.
Markdown is supported
0% or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment