【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.\n");
        exit(0);
    }
    
    if ((fp2 = fopen("new_hello.c", "w")) == NULL) {
        printf("Open file error.\n");
        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!\n");
        exit(0);
    }
    
    if (fclose(fp2)) {
        printf("Can not close the file!\n");
        exit(0);
    }
    
    
    return 0;
    
}

感觉写的比较烂,海涵了

 

posted @ 2021-09-29 15:18  就是想学习  阅读(56)  评论(0编辑  收藏  举报