preface
In the process of learning the operation of C language files, the author has encountered the following difficulties: because there are too many related functions given by the library function, the knowledge found in other articles is relatively comprehensive, and the author belongs to the group with weak memory ability, so I have to simplify and find two methods that use fewer library functions. This article will introduce them in detail, I hope it can help people who have such problems as the author.
In addition, due to the nature and positioning of this article, it is doomed to be incomplete. Please forgive me. If possible, the author will write other articles in the future for your detailed reference!
Since the author is used to using heap instead of array, this article will use the contents of heap (dynamic memory application). Students without relevant knowledge can use array or learn dynamic memory application in the process of practical operation. Here, the author provides you with an article written by the author to introduce dynamic memory application: link.
Necessary description of FILE *
FILE is a structure that contains some things related to FILE operation, while FILE * is a FILE pointer. Files are generally operated through this type of pointer.
It should be noted that whenever we read some characters, FILE * will move the corresponding characters backward
Introduction to required file class functions
This can't be reduced. We can only remember it honestly and skillfully
1. fopen (open file)
Prototype and introduction
FILE * fopen ( const char * filename, const char * mode );
Parameter 1: filename, as the name suggests, is the file name, which is filled in as a string
It should be noted that:
1. Remember to fill in the path for the file name. Don't be lazy
2. As can be seen from the prototype, you can fill in the pointer here or directly fill in the string
Parameter 2: mode, also fill in the string, which represents the opening method
Generally speaking, it can be opened in these ways:
1. "r", read only
2. "w", write only, but the data in the original file will be cleared after opening
3. "r +", read / write, open without emptying
4. "w +", read / write, open and clear
5. "a", added, added after the original foundation (I don't think it's very convenient, the reader depends on his own situation)
If the input file does not exist, a new file will be created in the form of "w" series, and a NULL will be returned in the form of "r" series
The above is to open a text file. To open a binary file, add a b after it, such as "rb", "wb +" (this article only introduces the text form)
Return value: pointer of type FILE *, pointing to the open FILE, or to the first character in the FILE
example
Example 1:
FILE* pf = fopen("C://DELL//test.txt","r+"); //It is not recommended that you put the documents on disk C. here are just examples
Example 2:
char arr[]="C://DELL//test.txt"; FILE* pf = fopen(arr,"r+"); //The effect is the same as that of example 1 above
2. fclose (close file)
Prototype and introduction
int fclose ( FILE * stream );
Parameter: stream, which is a pointer to the file to be closed
Return value: 0 if closing is successful, EOF (- 1) if closing fails
example
pf = fopen("C://DELL//test.txt","r+"); int a = fclose(pf); if(a==0){ printf("Closed successfully!"); pf = NULL; //Remember to make the pointer point to NULL after closing } else if(a==-1){ printf("Closing failed!"); }
3,fgetc
Prototype and Application
int fgetc ( FILE * stream );
Parameter: pointer to the file to be read
Return value: read the ascall code of the character
This function is similar to getchar, except that getchar is read from the keyboard and fgetc is read from the file
example
pf = fopen("C://DELL//test.txt","r+"); char c; c = fgetc(pf); printf("%c",c);
4,fprintf
The print function, a function similar to printf, only means that it is printed on the screen, but in the file
Prototype and Application
int fprintf ( FILE * stream, const char * format, ... );
Parameter: one more parameter than printf, that is, the first parameter: stream, is a pointer to the file to be printed
This is not an example. It has been made clear above.
Specific operation
1, Modify data in file
1. Load files into memory and realize visualization
This operation can make the following particularly simple, as follows:
// 1. We open the file in the form of "r" because we need to see the contents of the file FILE* pf = fopen("C://DELL//test.txt" , "r+"); // 2. We store the data in the file in memory // Note: // In this step, you can choose to use stack memory: that is, create a sufficiently large array // You can also choose to use heap memory: that is, apply for dynamic memory space //Here, I choose to use heap memory. The operation is as follows: char* arr = (char*)malloc(1); char ch; int i = 0; ch = fgetc(pf); do{ arr[i] = ch; i++; arr = (char*)realloc(arr,i + 1); ch = fgetc(pf); } while (ch!=EOF); arr[i] = '\0'; //This step is necessary. We need an end. The end of the string is' \ 0 ', and the end of the file will return' EOF ' // Visual operation is that we see the contents of the file, so we can type the string on the screen printf("%s",arr); // Remember to close the file after completing the "load file into memory" operation fclose(pf);
So far, all the contents of the file now exist in the string arr, and we can see that we just need to select the content we need to modify in the string, modify it and load it into the file. This is also our next operation
2. Modify data loaded in memory
This operation is equivalent to random access to the data in memory. In fact, the file type function has fseek, which can realize random access directly in the file, but 1 Random access to files is inefficient (i.e. slow!); 2. No visualization (can't see!); 3. That's what I said at the beginning of the article: novices have problems in mastering and memorizing functions. To sum up, it's quite unwise to access directly on disk. It's not only ineffective, but also difficult to master, so I don't recommend it. Of course, I personally recommend it.
OK, let's get to the point and realize:
// Due to the above operations, all the contents of the file will be printed on the screen. Remember that '\ n' (line feed) is also a character, which should not be ignored // We create a problem window to implement the change int c = 0; //Variable choose int e = 1; //Variable end, end condition while(1){ printf("\n Change?\n1,yes\n0,no\n"); scanf("%d",&e); if(e==0){ break; } printf("Enter the character sequence number you want to change:"); // Here we discuss the classification. If c is larger than the total number of characters and is regarded as additional characters, we include the last '\ 0', which is i+1 in total scanf("%d",&c); getchar();//Absorb extra '\ n' if(c>=i){ c = i; //Capacity expansion i++; arr=(char*)realloc(arr,i+1); arr[i]='\0';//Ensure the integrity of the string } // Then change the selection character printf("Characters you want to change:"); scanf("%c",&ch); arr[c] = ch; // Then, update the interface and type the modified system("cls"); printf("%s",arr); }
At this point, the modification is completed, and the next step is to load it into disk
3. Update to file
It's an easy and final step!
// We open the file and select the opening method of direct emptying, 'w' or 'w +' to write pf = fopen("C://DELL//test.txt","w+"); // Start entry fprintf(pf,"%s",arr); //After entering, remember to close the file and be a responsible program. fclose(pf); pf=NULL;
2, New file
As the title, this is relatively simple
1. Determine content
We also use string display. Stack area and heap area choose one according to their preferences. The author is used to using heap, so let's show heap!
char ch; char* arr; arr =(char*)malloc(1); ch = getchar(); int i = 0; int e = 1;//End end judgment variable while(1){ do{ arr[i] = ch; //Capacity expansion i++; arr=(char*)realloc(arr,i+1); //Reset ch ch=getchar(); }while(ch != '\n'); //At this time, we need to judge whether it is a line break or an end printf("What was the order just now?\n1,Line feed\n2,end\n); scnaf("%d",&e); if(e==0){ //Complete the end of the string arr[i] = '\0'; break; } }
So far, the input phase is over, and the following is the upload phase
2. Upload file
The simple steps are as follows
// We open the file and select 'w' or 'w +' write to create a new file FILE* pf = fopen("C://DELL//test.txt","w+"); // Start entry fprintf(pf,"%s",arr); //After entering, remember to close the file and be a responsible program. fclose(pf); pf=NULL;
Write it at the back
The author integrates his knowledge and perception into the article in the way of specific code. There are still many things worth thinking about (for newcomers). I hope it can help you!