1、接下来我们就以C语言线程写文件实例进行演示,首先,创建VS的空项目工程,如下图所示。
2、现在项目工程有了,需要在这个项目中创建C语言源文件,在项目右键,新建C语言源文件,如下图所示。
3、#include <stdio.h>#include <挢旗扦渌;stdlib.h>#include <string.h>#include <Windows.h>#define MAX_LINE 1024void WriteTxt(char* pFilePath){ char buf[MAX_LINE]; /*缓冲区*/ FILE *fp; /*文件指针*/ int len; /*行字符个数*/ if((fp = fopen(pFilePath,"at+")) == NULL) { perror("fail to read"); exit (1) ; } strcpy(buf, "1\n"); fputs(buf,fp); fclose(fp); return ;}static DWORD WINAPI thread1(LPVOID pParams){ int n = 0; while (1) { n++; printf("执行次数[%d]\n", n); Sleep(1500); WriteTxt("D:\\test.txt"); } return 0;}int main(){ DWORD dwThreadid = 0; CreateThread(NULL, 0, thread1, NULL, 0, &dwThreadid); getchar(); return 0;}
4、将上述参考代码拷贝到main.c文件下,如下所示。