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