C/C++ |
||||||||||||||||||
File I/O - Text
Reading a whole text file - fgetc() =============================================
Example 01 >
#include <stdio.h>
main() {
FILE *fp; char c;
fp = fopen("FileText_Ex01.txt", "r");
while(!feof(fp)) {
c = fgetc(fp); printf("%c", c);
}
fclose(fp);
}
Result :
Reading a whole text file - fgets() =============================================
Example 01 >
#include <stdio.h>
main() {
FILE *fp; char buff[255];
fp = fopen("FileText_Ex01.txt", "r");
while(!feof(fp)) {
fgets(buff, 255, (FILE*)fp) ; printf("%s", buff );
}
fclose(fp);
}
Result :
Example 02 >
#include <stdio.h>
main() {
FILE *fp; char buff[255];
fp = fopen("FileText_Ex01.txt", "r");
while(!feof(fp)) {
if(fgets(buff, 255, (FILE*)fp) != NULL) { printf("%s", buff ); }
}
fclose(fp);
}
Result :
Reading a whole text file - fscanf() =============================================
Example 01 >
#include <stdio.h>
main() {
FILE *fp; char buff[255];
fp = fopen("FileText_Ex01.txt", "r");
while(!feof(fp)) {
fscanf(fp,"%s",buff); printf("%s", buff);
}
fclose(fp);
}
Result :
Example 02 >
#include <stdio.h>
main() {
FILE *fp; char buff[255];
fp = fopen("FileText_Ex01.txt", "r");
while(!feof(fp)) {
fscanf(fp,"%s",buff); printf("%s\n", buff);
}
fclose(fp);
}
Result :
#include <stdio.h>
main() {
FILE *fp; char label1[20],label2[20]; float x,y;
fp = fopen("FileText_Ex02.txt", "r");
while(!feof(fp)) {
if(fscanf(fp,"%s %f %s %f",label1,&x,label2,&y) != 0) { printf("%s = %f, %s = %f\n", label1,x,label2,y); }
}
fclose(fp);
}
Result :
writing a text file - fpuc() =============================================
Example 01 >
#include <stdio.h> #include <stdlib.h>
int main() { FILE * fp;
char *s = "This is a text output sample"; char c;
fp = fopen ("TestFile.txt", "w");
do{ c = *(s++); fputc(c,fp); }while(c != '\0');
fclose(fp);
return(0); }
Result : TestFile.txt
Example 02 >
#include <stdio.h> #include <stdlib.h>
int main() { FILE * fp;
char *s = "This is a text output sample"; char c;
fp = fopen ("TestFile.txt", "w");
do{ c = *(s++); if(c == ' ') c = '\n'; fputc(c,fp); }while(c != '\0');
fclose(fp);
return(0); }
Result : TestFile.txt
writing a text file - fprintf() =============================================
Example 01 >
#include <stdio.h> #include <stdlib.h>
int main() { FILE * fp;
fp = fopen ("TestFile.txt", "w"); fprintf(fp, "This\nis\na\ntest\nfile\n"); fprintf(fp, "This is a test file\n"); fprintf(fp, "X %f Y %f",0.1,0.12345);
fclose(fp);
return(0); }
Result : TestFile.txt
|
||||||||||||||||||