我应该能够对文件进行排序: perl -e '打印排序 <>' 数据文件
我想做的是从 C 脚本调用此脚本。 C 脚本将数据文件名传递给 Perl 脚本,然后读取排序后的输出。
我已经准备好代码了:
#include <stdio.h>
FILE *popen(const char *command, const char *mode);
int pclose(FILE *stream);
int main(void){
FILE *cmd = popen("myperlscript myparams", "r");
char result[1024];
while (fgets(result, sizeof(result), cmd) != NULL)
printf("%s", result);
pclose(cmd);
return 0;
}
那么我如何将文件中的姓氏列表:data.txt 从 C 传递到 Perl,并将排序后的列表输出到标准输出? (它的 Perl 方面)?
最佳答案
只是替换
FILE *cmd = popen("myperlscript myparams", "r");
与
FILE *cmd = popen("perl -e 'print sort <>' data.txt", "r");
我建议你检查一下popen
的结果,使用这个:
#include <stdio.h>
#include <stdlib.h>
FILE *popen(const char *command, const char *mode);
int pclose(FILE *stream);
int main(void)
{
FILE *cmd;
char result[1024];
FILE *cmd = popen("perl -e 'print sort <>' data.txt", "r");
if (cmd == NULL) {
perror("popen");
exit(EXIT_FAILURE);
}
while (fgets(result, sizeof(result), cmd)) {
printf("%s", result);
}
pclose(cmd);
return 0;
}
Would it be possible to pass the file name in? (the data.txt) So I can read different file names?
当然,snprintf
和 main
的参数就是为此而生的;)
#include <stdio.h>
#include <stdlib.h>
FILE *popen(const char *command, const char *mode);
int pclose(FILE *stream);
int main(int argc, char *argv[])
{
char result[1024], str[128];
FILE *cmd;
if (argc != 2) {
fprintf(stderr, "Usage %s filename\n", argv[0]);
exit(EXIT_FAILURE);
}
snprintf(str, sizeof str, "perl -e 'print sort <>' %s", argv[1]);
cmd = popen(str, "r");
if (cmd == NULL) {
perror("popen");
exit(EXIT_FAILURE);
}
while (fgets(result, sizeof result, cmd)) {
printf("%s", result);
}
pclose(cmd);
return 0;
}
I'll actually be prompting the user to enter a filename once the program starts so passing in argv wouldn't work. (I believe, Very new to C) I could just change this to a perlSort function, and pass arguments that way, yes? To make this easier: ---Start Program ---Prompt user for source data file ---Prompt user for destination data file ---Display Menu: 1 - Sort with C 2 - Sort with Perl 3 - Find word with Perl
所以你想被灌输,好吧,没问题,但下次先自己努力,否则你永远学不会:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
FILE *popen(const char *command, const char *mode);
int pclose(FILE *stream);
int main(void)
{
char result[1024], tmp[128], *p;
FILE *cmd;
printf("Enter a filename: ");
fgets(tmp, sizeof tmp, stdin);
p = strchr(tmp, '\n');
if (p != NULL) *p = '\0';
snprintf(result, sizeof result, "perl -e 'print sort <>' %s", tmp);
cmd = popen(result, "r");
if (cmd == NULL) {
perror("popen");
exit(EXIT_FAILURE);
}
while (fgets(result, sizeof result, cmd)) {
printf("%s", result);
}
pclose(cmd);
return 0;
}
关于c - 用于对名称列表进行排序的 Perl 脚本,从 C 脚本传递的文件名,然后将排序后的列表传回,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26672211/