Linux的重定向到C程序 - 文件阅读 [英] Linux Redirection to C program - File Reading

查看:401
本文介绍了Linux的重定向到C程序 - 文件阅读的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想读从文本文件编号行( FILENAME.TXT )使用在C函数

我如何打开这个文件(提供的文件名,只有通过在Unix重定向给出)?


  

即。 ./cfile< FILENAME.TXT


  INT主要(无效)
{
  字符文件名[20];
  与fgets(文件名,19,标准输入);
  FILE * FP;
  FP = FOPEN(文件名,R);
}

那么,这是否正确;还了,我怎么访问的一行时从文件(我所知道的是EOF在某处被使用)?


解决方案

在Linux上,当你运行一个程序,3个文件被打开的标准输入(FD 0),输出(FD一)和错误(FD 2) 。默认情况下,这些文件是你的终端:

 %的猫和放大器;
 %ls -l命令的/ proc /`的pidof cat` / FD
共0
lrwx ------ 1最大最大64火星21 10:34 0 - >为/ dev / PTS / 0
lrwx ------ 1最大最大64火星21 10:34 1 - >为/ dev / PTS / 0
lrwx ------ 1最大最大64火星21 10:34 2 - >为/ dev / PTS / 0

但你也可以指定应该以<,> 2>使用的文件:

 %的猫>的/ dev / null的&安培;
 %ls -l命令的/ proc /`的pidof cat` / FD
共0
lrwx ------ 1最大最大64火星21 0 10:36 - >为/ dev / PTS / 0
L-WX ------ 1最大最大64火星21 10:36 1 - >的/ dev / null的
lrwx ------ 1最大最大64火星21 10时36分2 - >为/ dev / PTS / 0

因此​​,该文件已经被打开,分别是位于 FILE *标准输入标准输出标准错误。对于最后的例子是在标准输出,但在你的情况(以<)。它会在 FILE *标准输入

所以基本上,你不需要做的fopen ,您可以使用标准输入

I want to read lines of numbers from the text file (filename.txt) using a function in C.

How do I open this file (provided the filename is only given through a redirection on Unix)?

i.e. ./cfile < filename.txt

int main (void)
{
  char filename[20];
  fgets(filename, 19, stdin);
  FILE *fp;
  fp = fopen(filename, "r");
}

So, would this be correct; also, how do I access one line at a time from the file (all I know is EOF has to be used somewhere)?

解决方案

On Linux, when you run a program, 3 files are opened for the standard input (fd 0), output (fd 1) and error (fd 2). By default, these files are your terminal :

 % cat & 
 % ls -l /proc/`pidof cat`/fd
total 0
lrwx------ 1 max max 64 mars  21 10:34 0 -> /dev/pts/0
lrwx------ 1 max max 64 mars  21 10:34 1 -> /dev/pts/0
lrwx------ 1 max max 64 mars  21 10:34 2 -> /dev/pts/0

But you can also specify the file that should be used with <, > and 2> :

 % cat > /dev/null &        
 % ls -l /proc/`pidof cat`/fd
total 0
lrwx------ 1 max max 64 mars  21 10:36 0 -> /dev/pts/0
l-wx------ 1 max max 64 mars  21 10:36 1 -> /dev/null
lrwx------ 1 max max 64 mars  21 10:36 2 -> /dev/pts/0

So, the file is already opened and is respectively in the FILE* stdin, stdout and stderr. For this last example it's in stdout but in your case (with <) it will be in the FILE* stdin.

So basically, you don't need to do the fopen, and you can use stdin.

这篇关于Linux的重定向到C程序 - 文件阅读的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆