C/File/File Open
Содержание
Get file name from command line and open the file
#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;
}
Open a file and close it
#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;
}
Open a file for read
#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);
}
Open a file: how to use fopen
#include <stdio.h>
int main ()
{
FILE *file;
file = fopen ("my.txt","wt");
if (file!=NULL)
{
fputs ("Hiiiiiiiiiiiii",file);
fclose (file);
}
return 0;
}
Reopen a file
#include <stdio.h>
int main(void)
{
char str[80];
freopen("OUTPUT", "w", stdout);
printf("Enter a string: ");
gets(str);
printf(str);
return 0;
}
Reopen a stream with a different file and mode: how to use freopen
#include <stdio.h>
int main ()
{
freopen ("my.txt","w",stdout);
printf ("This line is redirected to a file.");
fclose (stdout);
return 0;
}