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;
    }

     

    一勤天下无难事。
  • 相关阅读:
    Qt5:快速设计对话框 QtDesigner 的使用
    Qt5:为菜单项添加图标 、 快捷键 和 状态栏 提示
    Qt5:在窗口上创建菜单栏
    Qt5:主窗口的创建 子类化QMainWindow
    AltiumDesigner设计快速入门
    AT24C02的MSP430驱动
    DSP_Builder设计方法说明_SinWave
    矩阵按键的MSP430驱动函数
    DAC8552使用说明
    PS2的FPGA解码模块
  • 原文地址:https://www.cnblogs.com/nowroot/p/12641270.html
Copyright © 2011-2022 走看看