当前位置:网站首页>6-7 file read / write operation

6-7 file read / write operation

2022-06-11 17:37:00 Tomatoes_ Menon

Write function , Read in by line from the given input text file , And write to the given output file by line . requirement :1) Remove leading spaces or tabs from each line .2) Add line number before each line .

Function interface definition :

void fileRW(FILE *fin,FILE *fout);

among fin and fout  All parameters passed in by the user , Are the pointers to the read in file and the output file respectively ( Opened as required ).

Sample referee test procedure :

#include <stdio.h>
void fileRW(FILE *fin,FILE *fout);
int main(){
    char fname[20];gets(fname);
        FILE *fpr=fopen(fname,"r");
      FILE *fpw=fopen("file2.txt","w");  
        fileRW(fpr,fpw);
        fclose(fpr);fclose(fpw);
    return 0;
}
/*  Please fill in the answer here  */

sample input :

Input file name :file1.cpp, The content is :

void fileW(){
	FILE *fp1=fopen("myfile.data","w");
	int i=123;float x=3.14159;
	fprintf(fp1,"%d,%5d,%5.3f\n",i,-i,x);
	fprintf(stdout,"%d,%5d,%5.3f\n",i,-i,x);
	fclose(fp1);
}

sample output :

file :file2.txt, The content is :

1:void fileW(){
2:FILE *fp1=fopen("myfile.data","w");
3:int i=123;float x=3.14159;
4:fprintf(fp1,"%d,%5d,%5.3f\n",i,-i,x);
5:fprintf(stdout,"%d,%5d,%5.3f\n",i,-i,x);
6:fclose(fp1);
7:}
void fileRW(FILE *fin,FILE *fout)
{
    char str;
    int i=1,j=1;
    do
    {
        str = fgetc(fin);//str Used to store the read string 
        if(i==j && str!=EOF)
        {
            fprintf(fout,"%d:",j++);//j Is the number of lines in the input file 
            while(str==' ' || str == '\t')
                str = fgetc(fin);
        }
        if(str == '\n')
            i++;//i Is the number of lines in the output file 
        if(str==EOF)
            break;
        fputc(str,fout);
    }
    while(1);// Read to the end of the file and return EOF It will end the cycle 
}

 

原网站

版权声明
本文为[Tomatoes_ Menon]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/162/202206111717105815.html