我的任务是从一个.c 文件中删除所有注释并将内容保存在另一个.o 文件中。
给定的文件:
// Sums two integers.
// Parameters: a, the first integer; b the second integer.
// Returns: the sum.
int add(int a, int b)
{
return a + b; // An inline comment.
}
应该看起来像:
int add(int a, int b)
{
return a + b;
}
我已经尝试了很多次,我达到了这个状态:
#include <stdio.h>
int main(int argc, char **argv)
{
FILE * fPtr;
fPtr = fopen("test.o", "w");
char line[300];
FILE *file = fopen("math_functions.c", "r");
if (file == NULL) {
printf("Error: Could not open %s!\n", "math_functions.c");
return -1;
}
else {
while(fgets(line, 300, file)) {
int len = strlen(line);
char helperLineArray[300];
for (int i = 1; i < len; i++) {
if (line[i] == '/' && line[i-1] == '/') {
break;
}
else
{
helperLineArray[i-1] = line[i-1];
}
}
fputs(helperLineArray, fPtr);
}
}
return 0;
}
提前致谢!
最佳答案
我想,这会有所帮助
FILE * fPtr;
fPtr = fopen("test.o", "w");
char line[256],helperLineArray[10000];
FILE *file = fopen("math_functions.c", "r");
int j=0;
while (fgets(line, sizeof(line), file)){
int len = strlen(line);
for (int i = 0; i < len-1; i++) {
if (line[i] == '/' && line[i+1] == '/') {
break;
}
else
{
helperLineArray[j++] = line[i];
}
}
helperLineArray[j++] = '\n';
}
fputs(helperLineArray, fPtr);
return 0;
关于c - 读取文件并将相同内容保存到新文件中,但不包含文件中的注释,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54724533/