问题描述
我想创建一个函数,给定一个字符串文件名,在 ./pid 目录中创建一个名为 filename.PID 的文件。
#define DEBUG 1
//PRINT_DEBUG just print the string in stderr
int CreatePidFile(char *filename){
if(DEBUG){
DEBUG_PRINT("CreatePidFile: start\n");
}
char *path = "./pid/";
char *post = ".PID";
FILE *pidfile;
char *pathfilename;
int N=strlen(path)+strlen(filename)+strlen(post)+1;
if((pathfilename=(char *)malloc(N*sizeof(char)))==NULL){
return -3;
}
strcpy(pathfilename,path);
strcat(pathfilename,filename);
strcat(pathfilename,post);
pathfilename[N-1]='\0'; //just to be sure that it has the final string char
if((pidfile = fopen(pathfilename,"w"))==NULL){
if(DEBUG){
DEBUG_PRINT("CreatePidFile: impossible to create il file\n");
}
free(pathfilename);
return -1;
}
int pid=getpid();
if((fwrite((void *)&pid,sizeof(int),1,pidfile))==0){
if(DEBUG){
DEBUG_PRINT("CreatePidFile: impossible to write pid in pidfile\n");
}
fclose(pidfile);
free(pathfilename);
return -2;
}
fclose(pidfile);
free(pathfilename);
if(DEBUG){
DEBUG_PRINT("CreatePidFile: end\n");
}
return 0;
}
我主要使用的是:
int main(){
printf("create pid: start\n");
char *filepid = "test_pid_file";
if((CreatePidFile(filepid))!=0){
printf("file not created\n");
}
else{
printf("test_utility: file is created\n");
}
return 0;
}
在程序结束时,文件被创建,但它是一个二进制文件。 我想要一个文本文件。
解决方法
好吧,您对 pid
进行了二进制写入:
fwrite((void *)&pid,sizeof(int),1,pidfile)
如果您想要文本,只需使用 fprintf
:
fprintf(pidfile,"%d",(int)pid);