在 C++ 中创建文件,就像按右键单击>新建>新建文本文档时一样

create a file in c++ like when you press right-click->new->new text document

本文关键字:gt 新建文本文档 新建 一样 单击 文件 创建 C++ 右键      更新时间:2023-10-16

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

只需这样做,在本例中,我使用键盘询问文件名,然后使用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 filenamen");
   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的路径。

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

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

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