C language file manipulation function freopen detailed parsing
- 2020-04-02 01:45:42
- OfStack
Do today USACO The operation of the file is used. Before doing USACO just format some write Freopen (" XXX. In ", "r", stdin) And "freopen (" XXX. Out", "w", stdout)"
Baidu baike is like this:
Function name: freopen
Can work: Replace a stream, or reallocate a file pointer, for redirection. If the stream is already open, close it first. If the stream is already directed, freopen clears the direction. This function is typically used to open a specified file to a predefined stream: standard input, standard output, or standard error.
Use method: FILE *freopen(const char *filename,const char *type, FILE *stream);
Header file: stdio.h
Case 1:
#include <stdio.h>
#include <stdlib.h>
int main()
{
if(freopen("file.txt","w",stdout)==NULL)
fprintf(stderr,"errorn");
printf("This is in the filen"); //This sentence will be displayed in file.txt.
fclose(stdout); //Using the fclose() function, the <A href = "http://baike.baidu.com/view/266782.htm" target = _blank> Buffer </ A> The last remaining data is output to a disk file and the file pointer and associated buffer are released.
return 0;
}
Example 2:
//First, create an in.txt text document under the same path and write some Numbers
#include <stdio.h>
#include <stdlib.h>
int main()
{
freopen("in.txt","r",stdin); //Read the data from in.txt
freopen("out.txt","w",stdout); //Write the final data to out.txt
int a,b;
while(scanf("%d%d",&a,&b)!=EOF) //The data was entered from in.txt
printf("%dn",a+b); //Write out. TXT
fclose(stdin);
fclose(stdout);
return 0;
}
Freopen (" CON ", "w", stdout) Represents writing data on the console window;
Example 3:
#include <stdio.h>
#include <stdlib.h>
int main()
{
// FILE *stream;
freopen("file1.txt","w",stdout);
printf("this is in file1.txt"); //This sentence is shown in file1.txt
freopen("CON","w",stdout);
printf("And this is in command.n"); //This sentence is displayed on the console
return 0;
}
Example 5: About fread Can be through the following procedures, a look to know what it means
#include <stdio.h>
#include <stdlib.h>
int main()
{
FILE *stream
char s[102400]="";
if((stream=freopen("file.txt","r",stdin))==null)
exit(-1);
fread(s,1,1024,stdin); //Read 1 to 1024 bits in file.txt and put them into s, which is my understanding
printf("%sn",s);
return 0;
}