c - 读取文件并将相同内容保存到新文件中,但不包含文件中的注释

标签 c

我的任务是从一个.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/

相关文章:

c - getopt_long() 和不是标志的参数?

C 文件写入和读取文件时 IO 额外字符

c - 如何在C中将PCM 8kHz 8位无符号转换为mp3

c - 分配还是不分配。大小 1 错误的读取无效。 【凝视2小时】

c - malloc行为解释

c - 字符串指针的子字符串指针

c - C : are these types identical technically, 中的类型声明等效还是只是实用上相同?

c - 在 C 中的链表中丢失部分

CMake 多个工具链和目标平台

c - Atoi/Atol - 结果为 0