From 3312e5de0edf35660c2c2a60bc1ddc81d91385af Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Toni=20R=C3=B6nkk=C3=B6?= Date: Tue, 26 Feb 2019 15:00:09 +0200 Subject: [PATCH] Output file to screen --- CMakeLists.txt | 1 + examples/cat.c | 85 ++++++++++++++++++++++++++++++++++++++++++++++++++ 2 files changed, 86 insertions(+) create mode 100644 examples/cat.c diff --git a/CMakeLists.txt b/CMakeLists.txt index 61ca8a1..b11e90b 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -35,6 +35,7 @@ add_executable (ls examples/ls.c) add_executable (locate examples/locate.c) add_executable (updatedb examples/updatedb.c) add_executable (scandir examples/scandir.c) +add_executable (cat examples/cat.c) # Build test programs include (CTest) diff --git a/examples/cat.c b/examples/cat.c new file mode 100644 index 0000000..cc88ff8 --- /dev/null +++ b/examples/cat.c @@ -0,0 +1,85 @@ +/* + * Output contents of a file. + * + * Compile this file with Visual Studio and run the produced command in + * console with a file name argument. For example, command + * + * cat include\dirent.h + * + * will output the dirent.h to screen. + * + * Copyright (C) 1998-2019 Toni Ronkko + * This file is part of dirent. Dirent may be freely distributed + * under the MIT license. For all details and documentation, see + * https://github.com/tronkko/dirent + */ +#define _CRT_SECURE_NO_WARNINGS +#include +#include +#include +#include +#include +#include + +static void output_file (const char *fn); + + +int +main( + int argc, char *argv[]) +{ + int i; + + /* Select default locale */ + setlocale (LC_ALL, ""); + + /* Require at least one file */ + if (argc == 1) { + fprintf (stderr, "Usage: cat filename\n"); + return EXIT_FAILURE; + } + + /* For each file name argument in command line */ + i = 1; + while (i < argc) { + output_file (argv[i]); + i++; + } + return EXIT_SUCCESS; +} + +/* + * Output file to screen + */ +static void +output_file( + const char *fn) +{ + FILE *fp; + + /* Open file */ + fp = fopen (fn, "r"); + if (fp != NULL) { + size_t n; + char buffer[4096]; + + /* Output file to screen */ + do { + + /* Read some bytes from file */ + n = fread (buffer, 1, 4096, fp); + + /* Output bytes to screen */ + fwrite (buffer, 1, n, stdout); + + } while (n != 0); + + /* Close file */ + fclose (fp); + + } else { + /* Could not open directory */ + fprintf (stderr, "Cannot open %s (%s)\n", fn, strerror (errno)); + exit (EXIT_FAILURE); + } +}