用c ++创建一个文件就像按下右键单击 - > new->新文本文档一样

时间:2013-09-05 12:54:39

标签: c++ c file createfile

使用从键盘读取的某个变量的名称,在某个目录中创建文件的C / C ++命令是什么? 例如:一个名为John的文本文件,以前从键盘上读取,该程序将创建文件John.txt

2 个答案:

答案 0 :(得分:0)

C方式:FILE* f = fopen(filename,"w");(假设您要写入它,否则第二个参数是“r”。)

C ++方式:std::fstream f(filename,std::ios::out);(假设你想写,读它的std :: ios :: in)

此外,在提出此类问题之前,请尝试搜索C / C ++文档。下次查看this网站。

答案 1 :(得分:0)

只需执行此类操作,在此示例中,我使用键盘询问文件名,然后使用fopen创建文件并将其传递给用户编写的文件名。

#include <stdio.h>
#include <string.h>

int main(){
   FILE *f;
   char filename[40], path[255];
   strcpy(path,"folder/path/"); //copies the folder path into the variable

   printf("Insert your filename\n");
   scanf("%s",&filename);

   strcpy(path,filename);
   f = fopen(path,'w'); //w is for writing permission   

   //Your operations
   fclose(f);
   return 0;
}

这是另一个使用POO的例子,它更适合C ++:

#include <iostream>
#include <fstream>

using namespace std;

int main () {
  string path = "my path";
  string filename;

  cout << "Insert your filename" << endl;
  cin >> filename;
  path = path + filename;

  ofstream f; 
  f.open (path.c_str()); //Here is your created file

  //Your operations
  f.close();
  return 0;
}

P.D:这个例子使用Unix的路径。