How to create a file only if it doesn't exist?

前端 未结 5 1305
庸人自扰
庸人自扰 2021-01-12 04:10

I wrote a UNIX daemon (targeting Debian, but it shouldn\'t matter) and I wanted to provide some way of creating a \".pid\" file, (a file which contains the process identifie

5条回答
  •  青春惊慌失措
    2021-01-12 04:28

    One way to approach this problem is to open the file for appending. If the function succeeds and the position is at 0 then you can be fairly certain this is a new file. Could still be an empty file but that scenario may not be important.

    FILE* pFile = fopen(theFilePath, "a+");
    if (pFile && gfetpos(pFile) == 0) { 
      // Either file didn't previously exist or it did and was empty
    
    } else if (pFile) { 
      fclose(pFile);
    }
    

提交回复
热议问题