window下遍历并修改文件

今天需要写一个遍历文件夹下的所有文件,试了试以前的方法竟然报错了。重新改了一下。

#include <iostream>
#include <stdlib.h>
#include <windows.h>
#include <fstream>
#include <iterator>
#include <string>
#include <time.h>
#include <math.h>
using namespace std; wchar_t* CharToWchar(const char* c)
{
wchar_t *m_wchar;
int len = MultiByteToWideChar(CP_ACP, , c, strlen(c), NULL, );
m_wchar = new wchar_t[len + ];
//映射一个字符串到一个宽字符(unicode)的字符串
MultiByteToWideChar(CP_ACP, , c, strlen(c), m_wchar, len);
m_wchar[len] = '\0';
return m_wchar;
}
char* WcharToChar(const wchar_t* wp)
{
char *m_char;
//映射一个unicode字符串到一个多字节字符串
int len = WideCharToMultiByte(CP_ACP, , wp, wcslen(wp), NULL, , NULL, NULL);
m_char = new char[len + ];
WideCharToMultiByte(CP_ACP, , wp, wcslen(wp), m_char, len, NULL, NULL);
m_char[len] = '\0';
//printf("my char %s\n", m_char);
return m_char;
} wchar_t* StringToWchar(const string& s)
{
const char* p = s.c_str();
return CharToWchar(p);
} void operate(string name)
{ ifstream file(name);
string tempStr;
int i = ; while (file) {
string line;
getline(file, line);
cout << line << endl;
if (line == "")break;
if (i == ) {
tempStr = line;
tempStr += "第一行加这个\n";
}
else {
tempStr += line;
tempStr += "其他行\n";
}
i++;
}
ofstream outfile(name, ios::out | ios::trunc);
outfile << tempStr << endl;
} int main()
{
int j = ;
char* Path = "files/*.*";
HANDLE hFile;
LPCTSTR lp = Path;
WIN32_FIND_DATA pNextInfo;
hFile = FindFirstFile(lp, &pNextInfo);
if (hFile == INVALID_HANDLE_VALUE) {
cout << "failed" << endl;
exit(-);//搜索失败
}
cout << "路径名:" << Path << endl; do {
//必须加这句,不然会加载.和..的文件而加载不了图片,
if (pNextInfo.cFileName[] == '.')continue;
string name = pNextInfo.cFileName;
cout << name << endl;
operate(".\\files\\"+name);
j++;
} while (FindNextFile(hFile, &pNextInfo));
system("pause");
return ; }

其中 files 为 文件夹名称。

程序功能: 遍历files下的所有文件,并在每行的末尾添加数据,第一行与其他行添加的内容不同。

上一篇:Python学习笔记基础篇——总览


下一篇:ld: warning: directory not found for option 去掉警告的方法