Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

How to realize File Operation in C language

2025-01-18 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/03 Report--

This article is about how to operate files in C language. The editor thinks it is very practical, so I share it with you. I hope you can get something after reading this article. Let's take a look at it with the editor.

What is a file?

The files on disk are files.

But in programming, we generally talk about two kinds of files: program files and data files (classified from the point of view of file function).

Program file

Includes source program files (such as .c files) target files (windows environment suffix .obj) executable programs (windos environment suffix exe).

Data file (focus of this article)

The content of the file is not necessarily the program, but the data read and written when the program is running, such as the file from which the program needs to read the data, or the file from which the content is output.

File name

A file is like a person, he must have a last name and first name to let other files or people know who the file is.

For each file, there is a unique file identity for users to identify and reference.

File name format: file path + file name trunk + file suffix

For example: d:\ CSDN\ Test.txt

For convenience, we call the file identification as the file name

Open and close file pointers to files

We know that the pointer points to an address, the shaping pointer points to a shaping space, and the array pointer points to the space of an array, so the file pointer is naturally a pointer to the file.

Each used file opens a corresponding file information area in memory, which is used to store the relevant information of the file (such as the name of the file, the status of the file and the current location of the file, etc.). This information is stored in a structural variable. The structure type is systematically declared and is named FILE.

This is the file information area structure under the stdio header file of vs.

Struct _ iobuf {char * _ ptr; int _ cnt; char * _ base; int _ flag; int _ file; int _ charbuf; int _ bufsiz; char * _ tmpfname;}; the FILE types of different C compilers of typedef struct _ iobuf FILE;// contain different content, but are more or less the same.

Just as a student needs to have information such as student ID, name and age, the file also has his information, such as the address of the file. This information is stored in this structure, renamed to FILE via typedef, and we don't need to care about the details (do you care what I ate last night).

Generally, a pointer to FILE is used to maintain the variable of the FILE structure, which is more convenient to use.

Below we can create a pointer variable for FILE*:

FILE* pf

Pf can access the file through the information in the information area of the file.

That is, the file associated with it can be found through the file pointer variable.

But the above file pointer does not point to a clear location, it is temporarily a wild pointer.

So next, let's learn how to open (create) a file.

File function

The file should be opened before reading and writing, and the file should be closed after use.

When writing a program, when you open a file, you will return a pointer variable of FILE* pointing to the file, which is equivalent to establishing a relationship between the pointer and the file.

ANSIC specifies that the fopen function is used to open the file and fclose to close the file.

/ / Open file FILE* fopen (const char * filename,const char * mode); / / the first parameter is the file name, and the second parameter is open method / / close file int Fclose (FILE* stream)

The partial opening mode is as follows

Now let's practice opening a file.

/ / Open the file FILE* pf = fopen ("data.txt", "r"); / / Open the file as read-only / / return empty if the file fails to open, otherwise it will return a pointer to the file if (pf = = NULL) {perror ("fopen"); return-1 } / / read the file / / close the file fclose (pf); pf = NULL; return 0

But failed to open it!

The reason is that, as we can see from the figure above, to open it in the "r" way, the file needs to be real, but I didn't create the file, so the opening failed.

Ding ~ the file was created successfully

Let's take a look at the implementation results.

There is no wrong report this time.

However, here I put the data.txt file in the .c file directory, and after I put the file somewhere else, I still opened the failure error.

The reason is that we only enter the file name in this code, so he only looks for the file in the current file directory, and we can't find the file anywhere else.

Here, let's look at two things, one is called relative path, the other is called absolute path.

Relative path and absolute path

Relative path

It is only considered to be a file in the current directory, as in the code above.

Absolute path

The path from disk to target file with the file

For example

D:\ Program Files\ data.txt

Note, however, that in programming,\ is an escape character, so we need to make\ no longer an escape character so that it represents itself

D:\ Program Files\ data.txt

Input and output stream

What is the input / output stream

If you have studied programming, you must know printf or cout or System.out.println

These functions are used to print data, which is the standard output stream. To make the data output or write to the file, we call it the output stream.

We print HELLO WORLD on the screen, which is a standard output stream.

Things like scanf, entering from a file or reading data into memory, is the input stream.

Some basic input and output functions are as follows.

For example, fputc is to write a character in, and fgetc is to read a character.

/ / Open the file FILE* pf = fopen ("data.txt", "w"); if (pf = = NULL) {perror ("fopen"); return-1;} / / read the file fputc ('baked, pf); fputc (' baked, pf); fputc ('clocked, pf) / / fputc the first parameter is the input character, and the second causes the corresponding file pointer / / to close the file fclose (pf); pf = NULL; return 0

Three characters of abc are written.

After fputc and fgetc read / write one character at a time, the file pointer pf moves backward, similar to the strtok function. The address of the last input / output is recorded.

If you don't, you'll be writing or reading files in one place all the time.

Next, let's take a look at fgetc reading characters.

/ / Open file FILE* pf = fopen ("data.txt", "r"); if (pf = = NULL) {perror ("fopen"); return-1;} / / read file int a = fgetc (pf); printf ("% c", a); a = fgetc (pf); printf ("% c", a) A = fgetc (pf); printf ("% c", a); / / close the file fclose (pf); pf = NULL; return 0

Execution result

This is reading and writing sequentially, reading and writing sequentially.

Of course, if there is sequential reading and writing, there will be random reading and writing.

As you can see from the literal meaning, emmm is read and written randomly.

Of course, except for fgetc, fgets naturally reads one line (only reads / writes one line).

If you use this type of function to output to standard input or standard input (stdout or stdin), it is no different from printf,scanf.

Next, let's look at binary reading and writing.

Binary read-write fwirte

Write the content to the file in binary form

The first parameter is the data address to which you want to write the data, and the second parameter is the size of a type (bytes). The third parameter is how many data you want to write, and the fourth is the stream you choose to write.

Struct S {int n; double d; char name [10];}; int main () {struct S s = {10,3.14, "zhangsan"}; / / Open the file FILE* pf = fopen ("data.txt", "wb"); if (pf = = NULL) {perror ("fopen"); return-1 } / / read the file fwrite (& s Magnesizeof (s), 1je pf); / / close the file fclose (pf); pf = NULL; return 0;}

The above code writes the data to data.txt in binary form

Although we can't understand it, we can see that zhangsan is what we typed.

Fread

Read in binary form

Like fwirte, except that buffer is not in the form of const, because we want to read the data into the target that the pointer points to.

Struct S {int n; double d; char name [10];}; int main () {struct S s = {0}; / / Open the file FILE* pf = fopen ("data.txt", "rb"); if (pf = = NULL) {perror ("fopen"); return-1 } / / read the file fread (& pf sizeof (struct S), 1djpf); printf ("% d% lf% s\ n", s.nmems.djournal s.name); / / close the file fclose (pf); pf = NULL; return 0;}

The above is how to achieve file operation in C language. The editor believes that there are some knowledge points that we may see or use in our daily work. I hope you can learn more from this article. For more details, please follow the industry information channel.

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report