Skip to content

Instantly share code, notes, and snippets.

@HappyCerberus
Created March 20, 2012 10:38
Show Gist options
  • Save HappyCerberus/2134019 to your computer and use it in GitHub Desktop.
Save HappyCerberus/2134019 to your computer and use it in GitHub Desktop.
Simple code snipet that will either use stdin, or the open the file received as the first runtime parameter.
/* Copyright (c) 2012 Mgr. Simon Toth ([email protected])
* Licensed under the MIT license: http://www.opensource.org/licenses/mit-license.php
*/
#include <stdio.h>
#include <stdlib.h>
int main(int argc, char *argv[])
{
FILE *input = stdin;
/* check if there is a command line parameter */
if (argc >= 2)
{
/* if there is, try to open it as file */
input = fopen(argv[1],"r");
if (input == NULL)
{
fprintf(stderr,"Couldn't open file \"%s\"\n",argv[1]);
return EXIT_FAILURE;
}
}
/* input is now either an open file, ready to be read from, or standard input */
/* cleanup */
if (input != stdin) fclose(input);
return EXIT_SUCCESS;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment