【C语言程序设计第四版】第十二章 程序设计题 6

第六题

输出文件中的注释:将C语言源程序(hello.c)文件中的所有注释去掉后存入另一个文件(new_hello.c)。

#include <stdio.h>
#include <stdlib.h>
#include <ctype.h>
#include <string.h>

#define MAXN 5000

int main(void){
    
    char ch, ch2;
    int w_signal, p_signal;
    w_signal = 1; p_signal=0; ch2=0;
    FILE *fp1, *fp2;
    if ((fp1 = fopen("hello.c", "r")) == NULL) {
        printf("Open file error.
");
        exit(0);
    }
    
    if ((fp2 = fopen("new_hello.c", "w")) == NULL) {
        printf("Open file error.
");
        exit(0);
    }
    
    while ((ch = fgetc(fp1)) != EOF) {
        if (ch == '"' && !p_signal) {
            w_signal = !w_signal;
        }
            
        if (w_signal && ch == '/' && !p_signal){
            ch2 = fgetc(fp1);
            if (ch2 == '*') {
                p_signal = 1;
            }
        }
        
        if (p_signal) {
            if (ch == '*') {
                ch2 = fgetc(fp1);
                if (ch2 == '/') {
                    p_signal = 0;
                    ch2 = 0;
                    continue;
                }
            }
        }
        
        
        if (!p_signal) {
            fputc(ch, fp2);
            if (ch2) {
                fputc(ch2, fp2);
                ch2 = 0;
            }
        }
        
    }
    
    
    if (fclose(fp1)) {
        printf("Can not close the file!
");
        exit(0);
    }
    
    if (fclose(fp2)) {
        printf("Can not close the file!
");
        exit(0);
    }
    
    
    return 0;
    
}

感觉写的比较烂,海涵了

原文地址:https://www.cnblogs.com/sidianok/p/15353042.html