Advocated said:
Just been searching google, but havent come up with anything. Just
wondering, whats the best way to print say a file.txt or other format to the
You could use the following C program...
#include <stdio.h>
#include <stdlib.h>
int main( int argc, char *argv[] )
{
char buf[256];
FILE *fp;
if( argc != 2 ) {
fprintf( stderr, "Usage: %s <filename>\n", argv[0] );
return EXIT_FAILURE;
}
if( (fp=fopen(argv[1],"r")) == NULL ) {
fprintf( stderr, "Could not open file \"%s\"\n", argv[1] );
return EXIT_FAILURE;
}
while( fgets(buf,sizeof buf,fp) ) {
printf( "%s", buf );
}
printf( "\n" ); /* in case there were no newlines in the file */
fclose( fp );
return EXIT_SUCCESS;
}
(salient comments from the regulars appreciated)
Where we have to use "clearerr()"?
#include <stdio.h>
#include <stdlib.h>
#if !defined(BUFSIZ)
#define BUFSIZ 256
#endif
/* here sizeof(buf)== BUFSIZ */
size_t rread(FILE* fp, char* buf, size_t* err)
{static size_t contar=0, re=0;
size_t con;
contar += (con=fread(buf, 1, BUFSIZ, fp));
if(ferror(fp))
{if(!re) {*err=contar; re=1;}
clearerr(fp);
}
return con;
}
/* here sizeof(buf)== BUFSIZ */
size_t wwrite(FILE* fp, char* buf, size_t* err, size_t num)
{static size_t contaw=0, wr=0;
size_t con;
contaw += (con=fwrite(buf, 1, num, fp));
fflush(fp);
if(!wr && con!=num)
{*err=contaw; wr=1;}
return con;
}
int read_write(FILE* fin, FILE* fout) /* fin and fout must be
opened first */
{char buf[BUFSIZ];
size_t yr=0, yw=0, num;
int c;
if(fin==stdout || fout==stdin || fin==0 || fout==0)
return -1;
if(ferror(fin))
clearerr(fin);
if(ferror(fout))
clearerr(fout);
if(feof(fin))
return 1; /* no errors */
do{num=rread(fin, buf, &yr);
if(num)
{wwrite(fout, buf, &yw, num); c=buf[--num]; }
}while(!feof(fin));
if(fout==stdout && c!='\n') c=fputc('\n', fout);
fflush(fout);
if(yr) fprintf( stderr, "Error in reading from %lu char\n",
(unsigned long) yr);
if(yw) fprintf( stderr, "Error in writing from %lu char\n",
(unsigned long) yw);
if(c==-1) fprintf( stderr, "Error in writing the last \\n ");
return c==-1 ? 0 : !(yr+yw) ;
}
void ricor(int c, char** a)
{FILE *fp;
if(a==0 || c<=0 || a[c]==0) return;
if( (fp=fopen(a[c],"r")) == NULL )
{fprintf( stderr, "I could not open file \"%s\"\n", a[c] );
ricor(++c, a);
return;
}
fprintf( stderr, "I writing the file \"%s\": \n", a[c] );
read_write(fp, stdout);
fclose(fp);
ricor(++c, a);
}
int main( int argc, char *argv[] )
{if( argc < 2 )
{fprintf(
stderr, "Usage: %s <filename_0> <filename_1> ... <filename_n>\n",
argv[0]!=NULL ? argv[0]: "This program "
);
return EXIT_FAILURE;
}
ricor(1, argv);
return EXIT_SUCCESS;
}