使用 argv 读取文件 [英] Read a file using argv

查看:32
本文介绍了使用 argv 读取文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当前代码正在读取文件并对记录进行排序,如下图,

#include"fileIO/file.h"#define MAX_RECORD_SIZE 256//错误的风格类型定义结构{年龄;字符 *姓氏;字符 *名字;}人;.....int main(int argc, char *argv[]){FILE *pFile = fopen("file.txt", "r");....callInsertionSort(getItemList(cache), getSize(getItemList(cache)), less);}

<小时>

哪里,file.txt 是,

年龄、姓氏、名字50,B,A30,A,B20,X,D10,F,A10,A,B90,V,E60,N,M

<小时><块引用>

执行:

$./sort.exe排序前年龄、姓氏、名字50 BA30 甲乙20 X 深10 FA10 甲乙90 伏特60 海里排序后年龄、姓氏、名字10 FA10 甲乙20 X 深30 甲乙50 BA60 海里90 伏特

<小时>

问题:

不使用 fopen(),有没有办法让 shell 将 file.txt 的内容作为命令行参数传递,每行一个参数文件,(通过argv通过传递shell命令(sort.exe)参数)?

解决方案

您可以将程序运行为:

IFS=$'\n'./sort.exe $(cat 文件.txt)

文件的每一行都将成为程序的一个参数(将 IFS 设置为换行符可防止文件中的空格成为参数分隔符).

然后程序可以循环argv(除了argv[0],它包含程序名)得到所有行进行排序.

请注意,参数的大小有限制,因此此方法的可扩展性不是很强.通常首选从文件中读取.

仅供参考,$(cat file.txt) 也可以写成$(

Currently the code is reading the file and sort the records, as shown below,

#include"fileIO/file.h"

#define MAX_RECORD_SIZE 256 // Bad style


typedef struct{
  int age;
  char *lastName;
  char *firstName;
}Person;

 .....



int main(int argc, char *argv[]){

  FILE *pFile = fopen("file.txt", "r");

  ....
  callInsertionSort(getItemList(cache), getSize(getItemList(cache)), less);

}


where, file.txt is,

Age,LastName,FirstName
50,B,A
30,A,B
20,X,D
10,F,A
10,A,B
90,V,E
60,N,M


Execution:

$./sort.exe
Before sorting
Age,LastName,FirstName
  50  B  A
  30  A  B
  20  X  D
  10  F  A
  10  A  B
  90  V  E
  60  N  M
After sorting

Age,LastName,FirstName
  10  F  A
  10  A  B
  20  X  D
  30  A  B
  50  B  A
  60  N  M
  90  V  E


Question:

Without using fopen(), is there a way to get the shell to pass the contents of file.txt as command-line arguments, one argument per line in the file, (through argv by passing shell command (sort.exe) parameters)?

解决方案

You can run the program as:

IFS=$'\n'
./sort.exe $(cat file.txt)

Each line of the file will then be an argument to the program (setting IFS to just newline prevents spaces in the file from being argument delimiters).

Then the program can loop over argv (except for argv[0], which contains the program name) to get all the lines to sort.

Note that there's a limit on the size of the arguments, so this method is not very scalable. Reading from the file is generally preferred.

FYI, $(cat file.txt) can also be written as $(< file.txt)

这篇关于使用 argv 读取文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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