C++

C/C++

文件操作

Posted by GY on December 15, 2018

输出数据到TXT文档中

#include <iostream>
#include <fstream>
using namespace std;

int main()
{
    int a = 10;
    float b = 10.0;
    ofstream dataFile;
    dataFile.open("dataFile.txt", ofstream::app);
    // 朝TXT文档中写入数据
    dataFile << "dataFile:" << a << "\n"
        << b << endl;
    // 关闭文档
    dataFile.close();
}

C/C++获取目录下文件或目录

Ubuntu

  在Unix/Linux系统中,要获取一个指定目录下所有的文件或文件夹,一般用dirent.h(POSIX标准定义的目录操作头文件)。

  • c
#include<stdio.h>
#include<dirent.h>
int main()
{
	DIR *dp;
	struct dirent *dirp;
	char dirname[256];
	printf("Please input a directory: ");
	scanf("%s",dirname);
	if((dp = opendir(dirname)) == NULL)
		printf("Can't open %s\n", dirname);
	while((dirp = readdir(dp)) != NULL)
		printf("%s\n", dirp->d_name);
	closedir(dp);
	return 0;
}
  • c++
#include<iostream>
#include<string>
#include<dirent.h>
using namespace std;

int main()
{
	string dirname;
	DIR *dp;
	struct dirent *dirp;

	cout << "Please input a directory: ";
	cin >> dirname;
	if((dp = opendir(dirname.c_str())) == NULL)
		cout << "Can't open " << dirname << endl;

	while((dirp = readdir(dp)) != NULL){
    //跳过'.'和'..'两个目录
    if(dirp->d_name[0] == '.')
        continue;
		cout << dirp->d_name << endl;
  }
	closedir(dp);
	return 0;
}

Windowns

void getAllFiles(string path, vector<string>& files) {
  //文件句柄
  long hFile = 0;
  //文件信息
  struct _finddata_t fileinfo;
  string p;
  if ((hFile = _findfirst(p.assign(path).append("\\*").c_str(), &fileinfo)) != -1) {
    do {
      if ((fileinfo.attrib & _A_SUBDIR)) { //比较文件类型是否是文件夹
        if (strcmp(fileinfo.name, ".") != 0 && strcmp(fileinfo.name, "..") != 0) {
          files.push_back(p.assign(path).append("\\").append(fileinfo.name));
          //递归搜索
          getAllFiles(p.assign(path).append("\\").append(fileinfo.name), files);
        }
      }
      else {
        files.push_back(p.assign(path).append("\\").append(fileinfo.name));
      }
    } while (_findnext(hFile, &fileinfo) == 0); //寻找下一个,成功返回0,否则-1
    _findclose(hFile);
  }
}