使用argv读取文件 [英] Read a file using argv
问题描述
当前代码正在读取文件并对记录进行排序,如下所示,
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);
}
file.txt
所在的位置
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
执行:
$./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:
在不使用fopen()
的情况下,有一种方法可以使外壳程序将file.txt
的内容作为命令行参数传递,文件中每行一个参数(通过argv
通过传递shell命令(sort.exe
)参数)?
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)
文件的每一行将成为程序的参数(将IFS
设置为仅换行符可防止文件中的空格成为参数定界符).
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).
然后,程序可以循环遍历argv
(argv[0]
除外,它包含程序名称)以对所有行进行排序.
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.
仅供参考,$(cat file.txt)
也可以写为$(< file.txt)
FYI, $(cat file.txt)
can also be written as $(< file.txt)
这篇关于使用argv读取文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!