文件1
:once:echo Hello # this is a comment
:once:echo 1
:once:echo 2
:once:echo 3
:once:echo 4
考虑上面的文件,如果我想逐行打印出每一行,我该如何删除“# this is a comment”和“:once:”
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main(int argc, char **argv) {
FILE *file = fopen(argv[1], "r");
char buf[100];
char p;
while (fgets(buf, sizeof(buf), file)) {
if ((p = strchr(buf, '#')))
*p = '\0';
printf("%s\n", buf);
}
fclose(file);
}
我想我可以使用 strchr 删除评论,但不确定如何去做。
我希望输出是这样的
$ gcc -Wall a.c
$ ./a.out file1
echo Hello
echo 1
echo 2
echo 3
echo 4
当前输出:
:once:echo Hello # This is a comment
:once:echo 1
:once:echo 2
:once:echo 3
:once:echo 4
不确定为什么会有额外的空间。我认为我对 strchr 有正确的方法,只是不确定如何使用。
最佳答案
你应该改变char p;
至 char *p;
,否则这根本行不通。如果您正在寻找 :once:
仅在一行的开头,您可以使用 strncmp()
检查前六个字符,并在必要时偏移字符串的开头。
此外,由于 fgets()
保留换行符,不妨加上\n
和 \0
当你遇到 #
符号,然后省略 \n
打印每一行时。这样你的输出就不会充满双换行符。
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main(int argc, char **argv) {
FILE *file = fopen(argv[1], "r");
char buf[100];
char *p;
while (fgets(buf, sizeof(buf), file)) {
if ((p = strchr(buf, '#'))) {
*(p++) = '\n';
*p = '\0';
}
printf("%s", buf + (strncmp(buf, ":once:", 6) == 0 ? 6 : 0));
}
fclose(file);
}
关于c - 如何从给定文件 C 中删除 '#' 符号,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49374965/