繁体   English   中英

使用C语言在Linux中的/ tmp文件夹中创建文本文件

[英]create text file in /tmp folder in Linux using c language

通过使用C语言,我需要在/tmp目录中创建一个文本文件,但是我不知道该怎么做。 有谁知道如何在/tmp文件夹中创建文本文件?

mkstemp函数

#include <stdio.h>  // Defines fopen(), fclose(), fprintf(), printf(), etc.
#include <errno.h>  // Defines errno

C程序通常以“ main()”函数开头。

int main()
   {
   int rCode=0;
   FILE *fp = NULL;

“ fp”将是对文件的引用,用于读取,写入或关闭文件。

   char *filePath = "/tmp/thefile.txt";

“ filePath”是一个字符串,其中包含路径“ / tmp”和文件名“ thefile.txt”。

下一行尝试以“写入”模式打开文件,(如果成功)将导致在“ / tmp”目录中创建文件“ thefile.txt”。

   fp=fopen(filePath, "w");

顺便说一下,在指定了“ w”(写入)模式的情况下,“ / tmp”目录中已经存在“ thefile.txt”,它将被覆盖。

如果无法创建文件,则以下代码将显示错误。

   if(NULL==fp)
      {
      rCode=errno;
      fprintf(stderr, "fopen() failed.  errno[%d]\n", errno);
      }

创建文件后,可以将其写入此处:

   fprintf(fp, "This is the content of the text file.\nHave a nice day!\n");

现在,可以关闭文件了。

   if(fp)
      fclose(fp);

全部做完。

   return(rCode);
   }  

这里取

#include <stdio.h>
int main ()
{
    FILE * pFile;
    pFile = fopen ("/tmp/myfile.txt","w");
    if (pFile!=NULL)
    {
          //write
         fclose (pFile);
     }
     return 0;
   }

如果/tmp/myfile.txt不存在,将创建一个。

这是一个例子:

char *tmp_file;
char buf[1000];
FILE *fp;

tmp_file = "/tmp/sometext.txt";

fp = fopen( tmp_file, "w" );

if ( fp == NULL ) {
  printf("File open error! %s", tmp_file );
}

sprintf( buf, "Hello" );

fputs( buf, fp );
fclose( fp );

其他几个人提到,执行此操作的正确方法是使用mkstemp()函数,因为这将确保您的文件具有唯一名称。

这是一个简单的用法示例:

//Set file name    
char filename[] = "/tmp/tmpfile-XXXXXX";

//Open the file in rw mode, X's replaced with random chars
int fd = mkstemp(filename);

//Write stuff to file...
write(fd, filename, strlen(filename));

//Close the file
close(fd);

//Do whatever else you want here, including opening and closing the file again

//Once you are done delete the temporary file
unlink(filename);

为了清楚起见,我故意省略了错误检查。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM