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("====\n");
    getchar();
    pthread_attr_destroy(&attr);
    return 0;
}
char* buf = "lock file ftrylockfile flick file\n";

void* Function_t(void* Param)
{
    FILE *fp = NULL;
    size_t ret;
    printf("Thread Starts.\n");
    pthread_t myid = pthread_self();
    ret = remove(FILE_NAME);
    if (ret == 0)
    {
        printf("删除文件成功\n");
    }
    else
    {
        printf("删除文件失败\n");
    }
    fp = fopen(FILE_NAME, "w+");
    if (fp == NULL)
    {
        printf("fopen file failure\n");
    }
    //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("删除文件成功\n");
    }
    else
    {
        printf("删除文件失败\n");
    }
    printf("ret is %d\n", ret);
    while (1)
    {
        Sleep(1000);
        printf("fopen file\n");

    }
    return NULL;
}

void* myFunction_t(void*MyParm)
{
    printf("Thread Starts.\n");
    pthread_t myid = pthread_self();

    while (1)
    {
        printf("my Function_t\n");
        Sleep(1000);

    }

    return NULL;
}

 

猜你喜欢

转载自www.cnblogs.com/nowroot/p/12641270.html