【发布时间】:2013-05-28 00:49:58
【问题描述】:
本来这个函数是嵌入到main函数中的,造成了一个非常杂乱的main函数。该程序用空格数替换制表符。我仍然对我的函数的参数列表中的内容以及如何将 argc/argv 从 main 传递到这些函数感到困惑。我这样做对吗?
文件顶部有一些已定义的变量:
#define OUTFILE_NAME "detabbed"
#define TAB_STOP_SIZE 8
#define NUM_ARGS 2
#define FILE_ARG_IDX 1
这是我的第二次尝试:
void open_file(FILE *inf, FILE *outf, char *in[]) /*I feel like the arguments aren't right
{ and this function is just opening
and reading files*/
inf = fopen(in[1], "r");
outf = fopen(OUTFILE_NAME, "w");
if (inf == NULL)
{
perror(in[1]);
exit(1);
}
else if (outf == NULL)
{
perror(OUTFILE_NAME);
exit(1);
}
fclose(inf);
fclose(outf);
}
void detab(FILE *infile, FILE *outfile, char *argument[]) /* Confused about argument list
{ and this function actually
char c; does the detabbing */
int character_count = 0, i, num_spaces;
open_file(infile, outfile, argument); /* I want to call the previous
function but again, confused
while (fscanf(infile, "%c", &c) != EOF) about the argument list */
{
if (c == '\t')
{
num_spaces = TAB_STOP_SIZE - (character_count % TAB_STOP_SIZE);
for (i = 0; i < num_spaces; i++)
{
fprintf(outfile, " ");
}
character_count += num_spaces;
}
else if (c == '\n')
{
fprintf(outfile, "\n");
character_count = 0;
}
else
{
fprintf(outfile, "%c", c);
character_count++;
}
}
}
int main(int argc, char *argv[])
{
if (argc < 1)
{
fprintf(stderr, "usage: prog file\n");
exit(1);
}
else if (argc < NUM_ARGS)
{
fprintf(stderr, "usage: %s file\n", argv[0]);
exit(1);
}
detab(argc, argv); /* I want to pass argc and argv to the detab function, but I'm
having trouble with the argument list */
return 0;
}
我需要帮助的是弄清楚函数的参数列表中的内容。我认为让我感到困惑的是如何让我的参数类型匹配,以便我可以将变量从一个函数传递给另一个函数。
【问题讨论】:
-
函数的存在是为了以后重用代码sn-ps。如果你的函数只被调用一次,我认为这可能是一个未成熟的优化。
-
@Summer_More_More_Tea No.
-
@H2CO3 谢谢,看看。
标签: c file space decomposition