zoukankan      html  css  js  c++  java
  • window多线程操作文件

                                                                                                使用c库操作文件

              

    #include "stdafx.h"
    #include <stdio.h>
    #include <pthread.h>
    #include <assert.h>
    #include <windows.h>
    #include <string.h>
    
    
    static void* Function_t(void* Param);
    static void* myFunction_t(void*MyParm);
    
    #define FILE_NAME   "D:\demo.txt"
    
    int main(int argc, _TCHAR* argv[])
    {
        pthread_t pid;
        pthread_attr_t attr;
        pthread_attr_init(&attr);
        pthread_attr_setscope(&attr, PTHREAD_SCOPE_PROCESS);
        pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_DETACHED);
        pthread_create(&pid, &attr, Function_t, NULL);
        pthread_create(&pid, &attr, myFunction_t, NULL);
        printf("====
    ");
        getchar();
        pthread_attr_destroy(&attr);
        return 0;
    }
    char* buf = "lock file ftrylockfile flick file
    ";
    
    void* Function_t(void* Param)
    {
        FILE *fp = NULL;
        size_t ret;
        printf("Thread Starts.
    ");
        pthread_t myid = pthread_self();
        ret = remove(FILE_NAME);
        if (ret == 0)
        {
            printf("删除文件成功
    ");
        }
        else
        {
            printf("删除文件失败
    ");
        }
        fp = fopen(FILE_NAME, "w+");
        if (fp == NULL)
        {
            printf("fopen file failure
    ");
        }
        //flockfile(fp);
        ret = fwrite(buf, 1, strlen(buf), fp);
        fflush(fp); // c库是有缓存区  所以需要有这个fflush  //fsync(fileno(fp)); // 文件指针转换fd  然后刷新到磁盘里面去
        fclose(fp);
        ret = remove(FILE_NAME); // 删除文件 
        if (ret == 0)
        {
            printf("删除文件成功
    ");
        }
        else
        {
            printf("删除文件失败
    ");
        }
        printf("ret is %d
    ", ret);
        while (1)
        {
            Sleep(1000);
            printf("fopen file
    ");
    
        }
        return NULL;
    }
    
    void* myFunction_t(void*MyParm)
    {
        printf("Thread Starts.
    ");
        pthread_t myid = pthread_self();
    
        while (1)
        {
            printf("my Function_t
    ");
            Sleep(1000);
    
        }
    
        return NULL;
    }

     

    一勤天下无难事。
  • 相关阅读:
    介绍几个程序员常去的网站
    你这辈子,为什么富不起来?!
    Bug解决:mysql 创建表字段Double类型长度
    RedisTemplate5种数据结构操作
    StringRedisTemplate与RedisTemplate区别
    Redis客户端信息的存取
    Anaconda安装pygame
    springboot启动报错
    idea上传项目到github
    Docker安装报错
  • 原文地址:https://www.cnblogs.com/nowroot/p/12641270.html
Copyright © 2011-2022 走看看