The contents of the file are stored as follows:
One 1122 0 1122 * * 0 0 222 0 222 * * 0 0 333 0 333 * * 0 0
By using the following several functions,,,,, fopen
fprintf
fscanf
fseek
ftell
.
The specific function prototype looks like this:
File*fopen (const char*filename,const char *mode);
int fprintf (file*stream,const char *format,...)
int fscanf (file* stream,const char *format,...)
int fseek (File*stream,long offset,int origin)
First, the data is written to the file in an append form.
The specific write code looks like this:
The width of each data to be specified when the primary write is not specified, and when the data for a row is modified, the modified length is greater than the length of the modification, affecting the next line in the file. After the width is made, the following content will not be affected as long as the modified length is not greater than the established width. (This is the point of attention)
FILE *fp=fopen ("Clientinfo.txt", "ar+");
Clientinfo info;
memset (&info,0,sizeof (Clientinfo));
..... /* Complete the assignment of the info structure
/fprintf (FP, "%10s%10s%10d%10s%10s%10s%10d%10d", info.id,info.nickname,\ info.online
, INFO.PWD,INFO.ENCRYP,INFO.IP,INFO.PORT,INFO.FD);
fprintf (FP, "\ n");
The code for the change is as follows, and the entire code is implemented in MFC:
FILE *fp=fopen ("Clientinfo.txt", "r+");
Clientinfo info;
Long Nline=0,n;
memset (&info,0,sizeof (Clientinfo));
int oldline=0;/* record The offset of the previous line in the matching position
/CString str;
while (N=FSCANF (FP,%s%s%d%s,%s%s%d%d), info.id,info.nickname,\
&info.online,info.pwd,info.encryp, INFO.IP,&INFO.PORT,&INFO.FD))!=eof)
{
str. Format ("%d", nline);
MessageBox (str);
if (strncmp (Info.id,id,id). GetLength ()) * * Find the location to modify/
{
oldline=nline;
break;
Nline=ftell (FP);
Fseek (Fp,oldline,seek_set);/* Navigate to the location to be modified, note that this position is the last read, so write the first line, the first row except the * * *
(oldline!=0)
{
fprintf (FP, "\ n");
}
fprintf (FP, "%10s%10s%10d%10s%10s%10s%10d%10d", info.id,info.nickname,\ info.online,info.pwd,info.encryp
, INFO.IP,INFO.PORT,INFO.FD);
fprintf (FP, "\ n");
Here is the revised data, modify the second row, no impact before and after the data.
One 1122 0 1122 * * 0 0 222f 0 222f * * 0 0 333 0 333 * * 0 0
Summarize
Using C to replace a line in a file this is basically the end, we have learned? Hope that the content of this article for everyone's study and work can bring certain help, if there is doubt, we can message exchange.