一、C++創建文件函數
C++標準庫提供了創建文件的函數,即ofstream類。它定義了以下兩個函數:
void open (const char *filename, ios_base::openmode mode = ios_base::out);
void close();
其中,open()函數用於打開一個文件,其中filename參數為文件名,mode參數為文件的打開模式,常用的有out、in、app等。close()用於關閉已打開的文件。
以下是創建文件的示例代碼:
#include <iostream>
#include <fstream>
using namespace std;
int main() {
// 創建一個文件
ofstream file("example.txt");
// 寫入文件
file << "This is a test.";
// 關閉文件
file.close();
return 0;
}
二、C++創建文件夾後拒絕訪問
在Windows系統下,如果要在程序中創建文件夾並寫入文件,需要在打開文件前設置文件夾的權限。否則,程序可能會報錯拒絕訪問。
以下是在Windows系統下創建文件夾並寫入文件的示例代碼:
#include <iostream>
#include <fstream>
#include <windows.h>
using namespace std;
int main() {
// 創建文件夾
CreateDirectory("example_folder", NULL);
// 設置文件夾權限
SetFileAttributes("example_folder", FILE_ATTRIBUTE_NORMAL);
// 創建文件
ofstream file("example_folder\\example.txt");
// 寫入文件
file << "This is a test.";
// 關閉文件
file.close();
return 0;
}
三、創建文件linux
在Linux系統下,可以使用預定義的open()函數創建文件。需要使用的頭文件是<fcntl.h>和<sys/types.h>。
以下是在Linux系統下創建文件的示例代碼:
#include <iostream>
#include <fcntl.h>
#include <sys/types.h>
#include <sys/stat.h>
using namespace std;
int main() {
// 創建文件
int file = open("example.txt", O_CREAT|O_WRONLY, S_IRWXU);
// 寫入文件
write(file, "This is a test.", 15);
// 關閉文件
close(file);
return 0;
}
四、C創建文件
在C語言中,可以使用fopen()函數創建文件。需要使用的頭文件是<stdio.h>。
以下是在C語言中創建文件的示例代碼:
#include <stdio.h>
int main() {
// 創建文件
FILE *file = fopen("example.txt", "w");
// 寫入文件
fprintf(file, "This is a test.");
// 關閉文件
fclose(file);
return 0;
}
五、C創建文件夾
在C語言中,可以使用mkdir()函數創建文件夾。需要使用的頭文件是<sys/stat.h>和<sys/types.h>。
以下是在C語言中創建文件夾的示例代碼:
#include <sys/types.h>
#include <sys/stat.h>
int main() {
// 創建文件夾
mkdir("example_folder", S_IRWXU);
return 0;
}
六、創建文件Linux
在Linux系統下,可以使用open()函數創建文件。需要使用的頭文件是<fcntl.h>和<sys/types.h>。
以下是在Linux系統下創建文件的示例代碼:
#include <fcntl.h>
#include <sys/types.h>
#include <sys/stat.h>
int main() {
// 創建文件
int file = open("example.txt", O_CREAT|O_WRONLY|O_TRUNC, S_IRWXU);
return 0;
}
七、C語言創建文件命令
C語言中除了使用函數創建文件外,還可以使用命令行來創建文件。需要使用的頭文件是<stdlib.h>。
以下是使用C語言命令行創建文件的示例代碼:
#include <stdlib.h>
#include <string.h>
int main() {
char command[50];
// 創建文件
strcpy(command, "touch example.txt");
system(command);
return 0;
}
八、C語言創建文件函數
在C語言中,可以使用fopen()函數創建文件。需要使用的頭文件是<stdio.h>。
以下是在C語言中創建文件的示例代碼:
#include <stdio.h>
int main() {
// 創建文件
FILE *file = fopen("example.txt", "w");
// 寫入文件
fprintf(file, "This is a test.");
// 關閉文件
fclose(file);
return 0;
}
原創文章,作者:小藍,如若轉載,請註明出處:https://www.506064.com/zh-hk/n/246907.html