C Language File Operation resolution
There are several more common operations in file operations, in addition to open operations and read and write operations. Here's a description of the functions involved in these operations.
I. Function to move a position pointer
The rewind function and the fseek function are prototypes of the two functions:
void Rewind (FILE *fp); Move the position pointer to the top of the file
int fseek (FILE *fp,long int offset,int origin); Move the position pointer to the offset byte number from Origin
For the arguments in the Fseek function, the origin is the starting point and the offset is the number of offsets from Origin
The value of the origin is three: Seek_set (0)-> file Head, Seek_cur (1)-> current position, Seek_end (2)-> file end.
Note: 1 If the file is opened by appending, the two functions will not work when the write is done, regardless of where the position pointer moves, append the added data to the end of the file.
Two. Other common functions
1.ftell function
Long int ftell (FILE *fp);
Calculates the number of bytes in the current position pointer from the top of the file, and returns -1L if an error occurs.
Use the Ftell function to calculate the size of a file.
2.feof function
int feof (FILE *fp);
Detects whether the current position pointer reaches the end of the file, returns a value other than 0 if it reaches the end of the file, or returns 0.
3.ferror function
int ferror (FILE *fp);
Detect error in file operation, if error, return a non 0 value, otherwise return 0
4.remove function
int remove (const char *filename);
Delete file, if delete succeeds, return 0, otherwise return non 0 value
5.rename function
int rename (const char *oldname,const char *newname);
Renames a file, returns 0 if the rename succeeds, or returns a value other than 0.
6.freopen function
file* freopen (const char *filename,const char *mode,file *stream);
Implement redirected input output. This function is used more when testing data.
7.fclose function
int fclose (FILE *stream);
Closes a stream, if successful, returns 0, otherwise returns-1. Note that the flow must be closed after each file operation, or data loss may result.
Test program:
#include <stdio.h>
#include <stdlib.h>
int main (void)
{
freopen ("Input.txt", "R", stdin );
Freopen ("Output.txt", "w+", stdout);
int i;
int a[10];
for (i=0;i<10;i++)
{
scanf ("%d", &a[i]);
for (i=0;i<10;i++)
{
printf ("%d\n", A[i]);
}
return 0;
}
Assuming that the engineering directory already exists Input.txt, the data in the file is 1 2-1 3 4 5 7 8 9 10, then after running, do not need to enter data from the console, the program reads the data directly from the Input.txt, and then outputs the results to the output.txt without directly outputting the results to the console.
Thank you for reading, I hope to help you, thank you for your support for this site!