Read file without fopen() (C language)

2020-04-08 14:39发布

问题:

I am working on a school project in which we have to do some operations (select, min, max) on a table saved in .txt file. The problem is that we can't use common functions such as fopen, fscanf, fclose.

The program will be launched from command line like this: .\project.exe select parameters <table.txt

Do you have some ideas how to get content of the .txt file to stdin without using fopen? Thanks.

回答1:

You do not need to open the file - the operating environment will do it for you.

When your program is called with <table.txt, your standard input is switched to read from that file instead of the keyboard. You can use scanf to read the data, and do not worry about opening and closing the file.

Same goes for the output of your program and the >table_out.txt redirection: rather than printing to the screen, printfs in your program would be writing to a file, which would be automatically closed upon your program's exit. Of course if you need to print something to the screen when your output is redirected, you can do so by printing to stderr (e.g. fprintf(stderr, "Invalid table format\n").



回答2:

There are few ways to acomplish this.

Reading STDIN

I guess the teacher wants this method in particular. The idea is reading standard input rather than particular file. In C++ you can simply read the stdin object. Here's an example:

#include <stdio.h>
#include <string.h>

int main(void)
{
  char str[80];
  int i;

  printf("Enter a string: ");
  fgets(str, 10, stdin);

  /* remove newline, if present */
  i = strlen(str)-1;
  if( str[ i ] == '\n')
      str[i] = '\0';

  printf("This is your string: %s", str);

  return 0;
}

Source: http://www.java2s.com/Code/C/Console/Usefgetstoreadstringfromstandardinput.htm

Using system utils

You can call "type" util @ Windows (not sure about it) or "cat" util in Linux as a subprocess to read some partticular file. But this is rather a "hack", so I do not recommend using this one.



标签: c file stdin fopen