c - How to add line numbers to the lines of existing file -
i need add line numbers each line of existitng file. idea read file1
add line number each line ,store in separate variable , write in file2
.
here code.
reading:
static char buff[100]; int linenum = 0; file *fp = fopen ("file1", "r"); while (fgets (buff, sizeof (buff), fp) != null) { printf ("%7d: %s %s ", ++linenum, buff); } fclose (fp);
saving :
i need store results above in " str " can written file2
file *fp2 = fopen ("file2", "w"); fwrite(str , 1 , sizeof(str) , fp2 ); fclose(fp2);
please give clear scenario, whatever understand use following sample code reference:
#include <stdio.h> #define max_line 1024 int main() { file *infile = null, *outfile = null; char lcharbuff[max_line]; int llinenum = 1; infile = fopen("main.c","r"); outfile = fopen("out.txt","w"); if(!infile || !outfile) { printf("unable open file\n"); return 0; } while(fgets(lcharbuff,max_line,infile) != null) { fprintf(outfile,"%10d %s",llinenum,lcharbuff); llinenum++; } fclose(infile); fclose(outfile); return 0; }
Comments
Post a Comment