【发布时间】:2014-07-16 15:48:40
【问题描述】:
以下代码未按预期工作..
#include <stdio.h>
#include <unistd.h>
#include <string.h>
#include <stdbool.h>
struct dest
{
char filename[20], keyword[20];
bool opened;
FILE * stream;
};
void display_data(const struct dest p) {
printf("Keyword: %s, Filename: %s, Used: %s\n", p.keyword, p.filename, p.opened ? "Yes" : "No");
}
int main(int argc, char const *argv[])
{
// float lon, lat;
// char info[80];
if ((argc+1) % 2) {
fprintf(stderr, "Usage: %s file_to_read file_for_unknown type file type file ...\n", argv[0]);
return 2;
}
if (access(argv[1], F_OK) == -1) {
fprintf(stderr, "File can't be accessed: %s\n", argv[1]);
return 2;
}
const short pairs = (argc-3)/2;
struct dest data[pairs];
short times = 4;
for(short i = 4; i < argc; i += 2) {
struct dest data[i-times];
data[i-times].opened = false;
strcpy(data[i-times].keyword, argv[i-1]);
strcpy(data[i-times].filename, argv[i]);
// display_data(data[i-times]);
times += 1;
}
display_data(data[0]);
return 0;
}
当我尝试运行它时会发生这种情况..
./categorize spooky.csv other.csv UFO UFOS.csv
关键字:?,文件名:�@,已使用:否
这没什么意义..
我一直在努力找出解决方案..静脉..
我不明白问题出在哪里..
参数解析如下:
第一个参数:程序应该读取的文件(暂时忽略)
第二个参数:程序应该存储的文件在 spooky.csv 文件 中找到的任何未知信息(也在此实现中被忽略)
其他参数:它们被成对解析,第一个是关键字,第二个是文件..
我对这个过滤问题的解决方案是创建一个结构数组,并在每个结构中存储关键字、文件名和文件 io 流(我暂时忽略)..
任何帮助将不胜感激..
【问题讨论】:
-
为什么是
if ((argc+1) % 2)而不是if (argc != NUM_ARGS_EXPECTED)?会更清楚。 -
@FiddlingBits 因为它应该接受尽可能多的参数,只要它们是从第二个参数开始的对..