线程复制图片和数组操作

本文展示了C语言中使用pthread创建并协同工作的两个线程,一个负责读取和复制文件内容,另一个用于线程安全地操作文件。代码实例包括对`stdio`,`pthread`,和文件I/O的使用。
摘要由CSDN通过智能技术生成

1.数组

 

 #include<stdio.h>
 #include<pthread.h>
 #include<unistd.h>
 #include<string.h>
 
 char buf[]="1234567";
 
 void*fun1(void*buf)
 {
     for(int i=0;i<10;i++)
     {
     printf("线程1=%s\n",(char*)buf);
 
     }
 }
 
 void *fun2(void*buf)
 {
     int len=strlen(buf)-1;
     for(int j=0;j<len/2;j++)
     {
         char temp;
         temp=((char*) buf)[j];
         ((char*) buf)[j]=((char*)buf)[len-j];
         ((char*)buf)[len-j]=temp;
     }
                                                          
 }
 
 int main(int argc, const char *argv[])
 {
     pthread_t pth_A;
     pthread_t pth_B;
     pthread_create(&pth_A,NULL,fun1,(void*)buf);
     pthread_create(&pth_A,NULL,fun2,(void*)buf);
 
 while(1);
 
     return 0;
 }
                                                          

2 复制图

#include<stdio.h>
#include<pthread.h>
#include<errno.h>
#include<unistd.h>
void* FUNC(void*i)
{
    FILE*fp=fopen("./1.png","r");

    FILE*my_fp=fopen("my.png","a+");
    fseek(fp,*(long*)i,SEEK_SET);

    size_t P;
    char date;
    while(1)
    {
        P=fread(&date,1,sizeof(date),fp);
        fwrite(&date,1,1,my_fp);
        if(P==0)
        {
            printf("读取完毕\n");
            break;
        }
    }
}
int main(int argc, const char *argv[])
{
    FILE*fp=fopen("./1.png","r");
    if(NULL==fp)
    {
        perror("fp");
        return -1;
    }
    FILE*my_fp=fopen("my.png","w");
    if(NULL==my_fp)
    {
        perror("my_fp");
        return -1;
    }

    //读取前半
    long LEN;
    fseek(fp,0,SEEK_END);
    LEN=ftell(fp);
    fseek(fp,0,SEEK_SET);
    char date;
    int PP;
    long i=0;
    while(i<LEN/2)
    {
        PP=fscanf(fp,"%c",&date);
        fprintf(my_fp,"%c",date);


        if(PP==EOF)
        {
            if(errno!=0)
            {
                perror("fscanf");
                return -1;
            }
            printf("复制完成\n");
            break;
        }
        i++;
    }
    fclose(fp);
    fclose(my_fp);



    //使用fread;________________

    /*      size_t P;
     *  P=fread(&date,1,sizeof(date),fp);
     fwrite(&date,1,1,my_fp);
     if(P==0)
     {      
     printf("读取完成\n");
     break;
     }*/

    //开线程——————————————————————————————————————
    pthread_t my_LINK;
    pthread_create(&my_LINK,NULL,FUNC,(void*)&i);
    pthread_join(my_LINK,NULL);
    fclose(fp);
    fclose(my_fp);


    return 0;                                          
}
                                                       

  • 6
    点赞
  • 10
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值