2017上学年课程设计2
来源:互联网 发布:foobar for mac 编辑:程序博客网 时间:2024/04/27 23:30
//读入一个C程序,使程序中的所有左花括号“{”和右花括号“}”都单独占一行,新程序保存到另一个.c文件中,并在屏幕上显示处理过的程序,显示时加上行号。#include <stdio.h>#include<string.h>#include<stdlib.h>void formatPrograme(char *sourcefile, char *targetfile);void outprogram(char *filename);int main( ){ formatPrograme("source.c", "target.c"); printf("处理后的程序是:\n"); outprogram("target.c"); return 0;}void formatPrograme(char *sourcefile, char *targetfile){ char ch1, ch2; //将文件中的数据读入到字符数组中 FILE *fpin=fopen(sourcefile,"r"); //以输入的方式打开文件 if(fpin==NULL) //测试是否成功打开 { printf("source code read error!\n"); exit(1); } FILE *fpout=fopen(targetfile,"w"); //以输入的方式打开文件 if(fpout==NULL) //测试是否成功打开 { printf("source code write error!\n"); exit(1); } ch1='\0'; while(!feof(fpin)) { ch2=fgetc(fpin); //读到了花括号,且前一个符号不是换行,应该加入一个换行 if((ch2=='{'||ch2=='}')&&(ch1!='\n')) fputc('\n', fpout); else //当前读到的不是换行,但前一个是花括号,此时也该加 if((ch1=='{'||ch1=='}')&&(ch2!='\n')) fputc('\n', fpout); fputc(ch2, fpout); //输出当前读入的符号 ch1=ch2; } fclose(fpout); fclose(fpin);}void outprogram(char *filename){ //建立一个字符数组存放文件的数据 char line[256]; //行数记录 int n=1; //将文件中的数据读入到字符数组中 FILE *fp=fopen(filename,"r"); //以输入的方式打开文件 if(fp==NULL) //测试是否成功打开 { printf("source code read error!\n"); exit(1); } while(!feof(fp)) { fgets(line,256, fp); //读入一行 printf("%d %s\n", n, line); n++; } fclose(fp); return;}
0 0