最初,这个函数被嵌入到主函数中,创建了一个非常困惑的主函数。该程序用空格数替换制表符。我仍然对我的函数的参数列表中包含的内容以及如何将 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;
}
我需要帮助的是找出函数参数列表中的内容。我认为让我感到困惑的是如何让我的参数类型匹配,以便我可以将变量从一个函数传递到另一个函数。
最佳答案
分解不是这里最大的问题。相当粗心的错误检查,使用旧的超重 fscanf()
和 fprintf()
和全局变量。此外,输入文件名缺乏 const 正确性、变量名过长和冗长以及您对 +=
和 ++
运算符的不了解只是额外的好处。我想这就是为什么您的代码看起来很臃肿(事实上确实如此)。
我会像这样重写函数:
void detab(const char *in, const char *out, int tabstop)
{
FILE *inf = fopen(in, "r");
if (!inf) return;
FILE *outf = fopen(out, "w");
if (!outf) {
fclose(inf);
return;
}
int n = 0;
int c;
while ((c = fgetc(inf)) != EOF) {
if (c == '\t') {
int pad = tabstop - n % tabstop;
for (int i = 0; i < pad; i++)
fputc(' ', outf);
n += pad;
} else if (c == '\n') {
fputc('\n', outf);
n = 0;
} else {
fputc(c, outf);
n++;
}
}
fclose(inf);
fclose(outf);
}
如果你想进一步分解它,那么你可以编写一个函数,将两个 FILE *
和制表位作为参数,它应该包含 while
仅循环 - 做这件事留给你作为练习。
关于c - 我尝试分解我的功能,但我不确定我是否做对了,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16870155/