一、 在给定的路径下创建文件:
1)在给定的路径下创建文件:
c++代码: #include using namespace std;int main(){
ofstream fout("E:/tide.txt");
fout <<"tide"<< endl;
}
打开文件的时候,一般有两种情况:
1)已经存在。下次打开的几种操作方式。
2)不存在的几种方式。
不存在的情况下,ofstream类的对象会默认创建一个同名文件;已经存在的情况下,ofstream类的对象会默认将该文件的内容删除,为数据输出到该文件做好准备。
文件的open函数:
ofstream file;
file.open(char * filename,int mode );
ios::in 打开文件进行读操作,即读取文件中的数据
ios::out 打开文件进行写操作,即输出数据到文件中
ios::ate 打开文件时文件指针指向文件末尾,但是你可以在文件中的任何地方写数据
ios::app 打开文件不会清空数据,文件指针始终在文件末尾,因此只能在文件末尾写数据
ios:trunc 默认,若打开文件已存在,测清空文件的内容
ios::nocreate 若打开文件不存在则不建立,返回打开失败信息
ios::noreplace 打开文件时不能覆盖,若文件存在测返回打开失败信息
ios::binary 打开文件为二进制文件,否则为文本文件
例子:
ofstream fout("E:\\linux.dat",ios::app);// 一种创建文件的方式。
这个代码的功能就是不存在的情况下创建文件,存在的情况下可以在文件的末尾添加数据。而不删除其中内容。
读取文件内容并输出代码:
#include #include #include int main () { char buffer[256]; ifstream file("test.txt"); if (! file.is_open()) { cout << "Error opening file"; exit (1); } while (!file.eof() ) { file.getline (buffer,100); cout << buffer << endl; } return 0; } //结果 在屏幕上输出文件的内容
2) .java实例代码:
import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.File; import java.io.FileReader; import java.io.FileWriter; import java.io.IOException; import java.io.PrintWriter; import java.io.RandomAccessFile; import java.util.Scanner;
import navigator.UI.MainFrame;//程序中引用的该程序的其他文件,不用考虑 public class historyfile {//自己建立的一个类hisoryfile private static final String fileName = "D://map//history.txt";//文件路径 public historyfile (String str,int str1,int str2) throws IOException{//构造函数 RandomAccessFile randomFile = new RandomAccessFile("D://map//history.txt", "rw"); long fileLength = randomFile.length(); randomFile.seek(fileLength);//将指针已到最后 String name =MainFrame.getMainFrame().UserName.getText(); //获取用户名 randomFile.writeBytes(name+"\r\n");//写入用户名 randomFile.writeBytes(str+"\r\n");//写入历史记录类型 randomFile.writeBytes(str1+"\r\n");//写入记录地点的下标 randomFile.writeBytes(str2+"\r\n");//写入第二个地点的下标(没有时写入0) randomFile.close(); } }
二、创建文件夹:
1)利用系统命令来创建文件夹:
系统命令 md + path即可创建文件夹
代码:
string path = "E:\\linux"; path = "md " + path; system(path.c_str());
系统命令创建文件夹,echo "创建文件夹">newtext.txt;