Read operations for files in C

Source: Internet
Author: User
Tags function prototype
read operations for files in C
File: The so-called "file" refers to an ordered set of related data. Data is stored as files on external media (typically disk, tape, CD-ROM, etc.), the operating system is in a file-based management of the data, with the file name as the identity of the access file.

The C language considers a file as a sequence of bytes, consisting of a series of bytes. Depending on the organization of data in the file, the data file can be divided into ASCII and binary files. An ASCII code file, also known as a "text file", contains an ASCII code for each byte. A binary file that stores the in-memory data on disk as it is stored in memory.

such as: decimal integer 10000, in memory accounted for two bytes, its storage form is: 00100111,00010000. It is also stored in binary files in this way. However, in an ASCII file, the decimal integer 10000 is stored as 31H, 30H, 30H, 30H, 30H, five bytes, which are 1, 0, 0, 0, 0, and 0 alphabetic ASCII codes.

C in the file read, only through the file pointer, the corresponding file can be called. Process of file operation: the operation of the disk file must be "open first, read after, and then close". The following is the use of a file pointer to open a file in a read-only open mode.

<span style= "White-space:pre" >	</span>file * FP;
	fp = fopen ("D://1//123.txt", "R");

The following is an analysis of the second parameter in the Fopen function using the file mode category,

Using file Mode

Meaning

"R" (read-only) Open a text file for input
"W" (write only) Open a text file for output
"A" (append) Open a text file for append
"RB" (Read only) Open a binary file for input
"WB" (write only) Open a binary file for output
"AB" (Append) Open a binary file for append
"R+" (Read and write) Open a text file for read/write
"w+" (Read and write) Create a text file for read/write
"A +" (Read/write) Open a text file for read/write
"Rb+" (Read and write) Open a binary file for read/write
"Wb+" (Read and write) Create a binary file for read/write
"Ab+" (Read and write) Open a binary file for read/write

Note: 1, if the use of the file mode is "a", means to add new data to the end of the file (do not delete the original data), but the requirement at this time the file must exist, or error, but I am debugging in the VS2010, the file does not exist, will automatically create a file, will not error, You can also write data to a file that cannot read the data in the file. If you use the file as a "A +" means to add new data to the end of the file (do not delete the original data), the file does not exist, will automatically create a file, no error, in addition to this file method, the open file can be used to input data, can also be used to output data.
2. Files opened with the "W" method can only be used to write data to the file. If the file does not already exist, create a new file when it is opened and, if it exists, delete the file (where the data is definitely deleted), and then reestablish a new file.
3, if the use of file mode for "w+" and "w", if the file does not exist, then create a new file when opened, if the file exists, delete the file (where the data is definitely deleted), and then re-establish a new file.
4, if the use of file mode for "r+", the file must exist, to write data to the file, do not delete the file, but directly overwrite, can cover how much coverage, the previous data will not overwrite the file still exists.
Use file mode as "r+" to store data in the file:
int main (void)
{

	FILE * FP;
	if (fp = fopen ("D://1//123.txt", "r+")) = = NULL)
	{
		printf ("Can not open the file\n");
		Exit (0);
	}

	Char str[] = "He fei wo Yao Liu xia1";

	int len = strlen (str);
	for (int i = 0; i < len;i++)
	{
		FPUTC (STR[I],FP);
	}
	Fclose (FP);
	return 0;
}


Use file mode as "r+" to read data from a file
int main (void)
{

	FILE * FP;
	if (fp = fopen ("D://1//123.txt", "r+")) = = NULL)
	{
		printf ("Can not open the file\n");
		Exit (0);
	}

	char ch = fgetc (FP);

	while (ch! = EOF)//Read data from a text file

	{
		putchar (CH);

		ch = fgetc (FP);
	}
	Fclose (FP);
	return 0;
}

For text files, the end-of-file sign EOF is returned at the end of the file. For binary files, use feof (FP) to determine if the end of the file, feof (FP) =1 description of the end of the file.

The contents of the file are read sequentially from the text file and displayed on the screen, and can be used:

ch = fgetc (FP);
while (ch! = EOF)
{
    putchar (CH);
ch = fgetc (FP);
  }

To read the contents of a file sequentially from a binary file, you can use:

while (!feof (FP))
{
ch = fgetc (FP);
}
If you write the data in the file, if you do not close the contents of the file directly read, there will be an error-after writing the file, not closed, then the file pointer in the last position, then you read the time must be from the end ah, so it is random characters, this will appear garbled. How to correct, and so on after the file finished writing data, first close the file, then read the file, you can, as follows Fclose (FP);
fp = fopen ("D://1//123.txt", "r+");

Read-write String functions are described below: Fgets and fputs:
1, read the string function fgets function function: Read a string from the specified file into a character array, the function call form: fgets (character array name, n, file pointer), where n is a positive integer. Indicates that a string that is read from a file does not exceed n-1 characters. After the last character read, add the string end flag ' \ s '. For example: Fgets (STR,N,FP), the meaning is to read from the file referred to in the FP n-1 characters into the character array str.
Attention:
A, before the n-1 characters are read, such as a newline character or EOF is encountered, the end of the read, but not the end of the space encountered.
b, the Fgets function also has a return value whose return value is the first address of a character array.
int main (void)
{
	FILE *fp;
	Char str[12];
	if ((Fp=fopen ("D://1//123.txt", "RT")) ==null)
	{
		printf ("Cannot open file!");
		Exit (0);
	}

	Fgets (STR,12,FP);
	printf ("%s", str);
	Fclose (FP);


	return 0;
}

2, write String function fputs function function: Write a string to the specified file, which is called as: fputs (string, file pointer) where the string can be a string constant, or it can be a character array name or pointer variable, for example: Fputs ("ABCD", FP);
int main (void)
{
	FILE *fp;
	Char ch,st[20];
	if ((Fp=fopen ("D://1//123.txt", "A +") ==null)
	{
		printf ("Cannot open file!");
		Exit (0);
	}

	printf ("Input a string:\n");
	scanf ("%s", St);
	Fputs (ST,FP);
	Rewind (FP);//The pointer to the file stream points to the beginning of the position
	ch=fgetc (FP);
	while (ch!=eof)
	{
		putchar (CH);
		CH=FGETC (FP);
	}

	Fclose (FP);
	return 0;
}

The following describes the formatting functions in the file fscanf and fprintf

1, fscanf
A, function prototype:
int fscanf (FILE *fp,char *format,arg_list)
B, Function description
Outputs the data in the file specified by the FP to the corresponding variable in the Variable table column (arg_list) in the format specified by format. FSCANF encounters a space and line break to end. Indicates that a space or line break is encountered, and the corresponding data in the file is read end. C, note that the data in the file is separated by commas, and the specified format in the corresponding formats is separated by commas. At this point I run an error in VS2010. D, the return value successfully returns the number of parameters read in, and the failure returns EOF (-1).
void Main ()
{
	file* fp;
	if (fp = fopen ("D://1.txt", "r+") ==null)
	{
		printf ("Can not open the file");
		Exit (1);
	}
	int A;
	Double b;
	Char c[15];
	FSCANF (FP, "%d%lf%s", &a,&b,c);

	printf ("%d", a);
	printf ("%lf", b);
	printf ("%s", c);
}

2, fprintf

A, function prototype:

int fprintf (FILE *fp,char *format,arg_list)
B, Function description
Writes the data in the Variable table column (arg_list) to the file specified by the FP in the format indicated by format. The fprintf () function is the same as the printf () function, except that the printf () function writes data to the screen file (stdout). The fprintf function converts the in-memory data into corresponding characters in a format and outputs it to a text file in the form of Ascⅱ code.
C, Parameter description
FP: This is a file pointer that indicates the file to write data to.
Format: This is a pointer to a character string that contains the format in which the data is to be written, so the string becomes a format string. The format string describes the same rules as the format string in the printf () function.
Arg_list: Is the variable table column to write to the file, separated by commas.

D, return value

The number of characters to output, and a negative value when an error occurs.

void Main ()
{
	file* fp;
	if (fp = fopen ("D://1.txt", "wb+") ==null)
	{
		printf ("Can not open the file");
		Exit (1);
	}
	int a = +;
	Double b = 6.5;
	Char c[15] = "Tansheng";
	fprintf (FP, "%d%lf%s", a,b,c);

}

There are spaces or commas in the fprintf format string, corresponding spaces or commas are also available in the file.

The fprintf and FSCANF functions are easy to read and write to disk files, but because the ASCII code is converted to binary form at input, it takes more time to convert the binary form into characters at the output. Therefore, it is best not to use the Fprinf and FSCANF functions, but with fread and fwrite, in cases where memory and disk are frequently exchanged for data.







Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.