使用 exec 对 c 中的文本文件进行排序
我有一个充满记录的文本文件 (output.txt),我想按 ID 对每个记录进行排序。排序后,排序后的记录将写入新文件(sorted.txt)。
为此,我通过 execl() 函数使用 bash 的命令“sort”。为了检查排序命令的有效性,我将相同的命令直接写入 bash,结果是预期的。但是当我尝试通过我的 C 程序使用 execl 命令时,大多数时候答案是没有文件 /usr/bin/sort (我使用的是 Mac OSX)或者不会抛出错误消息,但尽管如此什么也没发生... 我正在使用的是这样的:
execl("/usr/bin/sort", "usr/bin/sort", "-n","-k", "1", "-u", "output.txt", ">", "sorted.txt", (char*)NULL);
或者
execl("/usr/bin/sort", "usr/bin/sort", "-n","-k", "1", "-u", "-o", "sorted.txt", "output.txt", (char*)NULL);
我知道当我在 bash 中使用这两个排序命令时它们都是正确的。 C 会发生什么事? 提前谢谢大家!
I have a text file full of records (output.txt) and I want to sort every record by its id. After the sorting the sorted records are written into a new file (sorted.txt).
To do that I am using bash's command "sort" via an execl() function. To check the validity of my sort command, I wrote the same command straight into the bash and the result is the expected one. But when I try to use the execl command through my C program, most of the time the answer will be that there is not a file /usr/bin/sort (I am using Mac OSX) or no error message will be thrown but nevertheless nothing happens...
What I am using is this:
execl("/usr/bin/sort", "usr/bin/sort", "-n","-k", "1", "-u", "output.txt", ">", "sorted.txt", (char*)NULL);
or this
execl("/usr/bin/sort", "usr/bin/sort", "-n","-k", "1", "-u", "-o", "sorted.txt", "output.txt", (char*)NULL);
I know that both of these 2 sort commands are correct when I m using them in the bash. What happens to C?
Thnx all in advance!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
输出重定向(
> somefile.txt
)是 shell 的一项功能,而不是排序程序(AFAIK 不是 bash 内置的)。exec
系列函数不会启动 shell,只会启动您指定的程序。如果您不知道程序的路径,您可以使用名称中带有
p
的函数(我认为在您的情况下是execlp
),然后给它们 < code>"sort" 作为程序名称,它们会像 bash 一样在 $PATH 中搜索它。Output redirection (
> somefile.txt
) is a feature of the shell, not the sort program (which AFAIK is not a bash built-in).The
exec
family of functions doesn't start the shell, only the program you've specified.If you don't know the path to the program, you can use the functions with
p
in their names (execlp
in your case, I think) and just give them"sort"
as program name, they'll search for it in $PATH like bash does.或者,您可以尝试
system("sort output.txt >sorted.txt")
。system
函数的行为取决于实现,但在 Linux 上它基本上会生成一个新的 shell 来执行传递给它的命令。system(ARG)
相当于sh -c ARG
。如果 shell 在系统的system
函数实现中支持重定向,则重定向将起作用。Alternatively you can try
system("sort output.txt > sorted.txt")
. Thesystem
function's behaviour is implementation dependent though on linux it basically spawns a new shell which executes the command passed to it.system(ARG)
is equivalent tosh -c ARG
. The redirection will work if the shell supports it in your system's implementation of thesystem
function.