Tutorial by Examples

#include <stdio.h> /* for perror(), fopen(), fputs() and fclose() */ #include <stdlib.h> /* for the EXIT_* macros */ int main(int argc, char **argv) { int e = EXIT_SUCCESS; /* Get path from argument to main else default to output.txt */ char *path = (argc > 1...
You can use fprintf on a file just like you might on a console with printf. For example to keep track of game wins, losses and ties you might write /* saves wins, losses and, ties */ void savewlt(FILE *fout, int wins, int losses, int ties) { fprintf(fout, "Wins: %d\nTies: %d\nLosses: %d...
#include <stdio.h> void print_all(FILE *stream) { int c; while ((c = getc(stream)) != EOF) putchar(c); } int main(void) { FILE *stream; /* call netstat command. netstat is available for Windows and Linux */ if ((stream = popen("netstat", &qu...
The POSIX C library defines the getline() function. This function allocates a buffer to hold the line contents and returns the new line, the number of characters in the line, and the size of the buffer. Example program that gets each line from example.txt: #include <stdlib.h> #include <s...
#include <stdlib.h> #include <stdio.h> int main(void) { result = EXIT_SUCCESS; char file_name[] = "outbut.bin"; char str[] = "This is a binary file example"; FILE * fp = fopen(file_name, "wb"); if (fp == NULL) /* If an erro...
Let's say we have a text file and we want to read all words in that file, in order to do some requirements. file.txt: This is just a test file to be used by fscanf() This is the main function: #include <stdlib.h> #include <stdio.h> void printAllWords(FILE *); int main(void...
The stdio.h header defines the fgets() function. This function reads a line from a stream and stores it in a specified string. The function stops reading text from the stream when either n - 1 characters are read, the newline character ('\n') is read or the end of file (EOF) is reached. #include &l...

Page 1 of 1