C/File/File Open
Содержание
Get file name from command line and open the file
<source lang="cpp">
- include <stdio.h>
- include <stdlib.h>
int main(void) {
FILE *fp; char fname[128]; printf("Enter filename: "); gets(fname); if((fp=fopen(fname, "r"))==NULL) { printf("Cannot open file.\n"); exit(1); } fclose(fp); return 0;
}
</source>
Open a file and close it
<source lang="cpp">
- include <stdio.h>
- include <stdlib.h>
int main(void) {
FILE *fp; if((fp = fopen("test", "rb")) == NULL) { printf("Cannot open file.\n"); exit(1); } if( fclose( fp )) printf("File close error.\n"); return 0;
}
</source>
Open a file for read
<source lang="cpp">
- include "stdio.h"
int main() {
FILE *fp; int letter; if( ( fp = fopen( "my.txt", "r")) == NULL) { puts("Cannot oepn the file"); exit( 0 ); } while( ( letter = fgetc( fp ) ) != EOF) printf("%c",letter); fclose(fp);
}
</source>
Open a file: how to use fopen
<source lang="cpp">
- include <stdio.h>
int main () {
FILE *file; file = fopen ("my.txt","wt"); if (file!=NULL) { fputs ("Hiiiiiiiiiiiii",file); fclose (file); } return 0;
}
</source>
Reopen a file
<source lang="cpp">
- include <stdio.h>
int main(void) {
char str[80]; freopen("OUTPUT", "w", stdout); printf("Enter a string: "); gets(str); printf(str); return 0;
}
</source>
Reopen a stream with a different file and mode: how to use freopen
<source lang="cpp">
- include <stdio.h>
int main () {
freopen ("my.txt","w",stdout); printf ("This line is redirected to a file."); fclose (stdout); return 0;
}
</source>