C语言文件io修改指定位置的数据(用户名和密码)

1、首先,文本中每行存储一名用户的数据,比如ssl123

2、while(!feof())判断文件末尾,fscanf进行遍历,每次获取一行,即一名用户的数据

3、用户根据用户名进行修改,ssl,使用strstr进行匹配,匹配成功strlen获取这行数据的长度

4、fseek(文件指针,-(len+1), SEEK_CUR)往前偏移至文本(要修改的数据的)开头

5、sacnf获取用户的新数据,比较新旧数据的大小,进行补空格覆盖或者其他操作

6、最后fprintf覆盖写入,即大功告成!

#include <sys/types.h>		
#include <unistd.h>			
#include <stdio.h>			
#include <sys/wait.h>		
#include <stdlib.h>		
#include <string.h>			
#include <strings.h>		
#include <sys/stat.h>		
#include <fcntl.h>			 
#include <signal.h>		
#include <sys/ipc.h>		
#include <sys/msg.h>		
#include <sys/shm.h>		
#include <sys/sem.h>		
#include <pthread.h>		
#include <sys/mman.h>		
#include <dirent.h>			
#include <linux/input.h>	
#include <time.h>			
#include <math.h>			
#include <stdbool.h>		
#include <semaphore.h>		
#include <errno.h>
#include <sys/socket.h>     
#include <arpa/inet.h>      
#include <netinet/in.h>
#include <netinet/ip.h>
void traverse_send(char *path,char *name)//目录检索
{
    char msg[100];
    char buf[100];
    //打开文件
    FILE *fd = fopen(path,"r+");
    //先发一个特殊标识
    while (!feof(fd))//判断文件末尾
    {
        bzero(msg,20);
        fscanf(fd,"%s\n",msg);
        if (strstr(msg,name) != NULL)//找到指定用户
        {
            int len = strlen(msg);
            fseek(fd,-(len+1),SEEK_CUR);
            printf("请输入用户名和密码:");
            bzero(buf,100);
            scanf("%s",buf);
            if (strlen(buf) < len)
            {
                buf[strlen(buf)] = ' ';
            }
            fprintf(fd,"%s\n",buf);
        } 
    }
    fclose(fd); 
    
}

int main(int argc, char const *argv[])
{
	traverse_send("./1.txt","xhf");//目录检索
	return 0;
}

txt文本如下

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值