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, 0, c, strlen(c), NULL, 0);
    m_wchar = new wchar_t[len + 1];
    //映射一个字符串到一个宽字符(unicode)的字符串
    MultiByteToWideChar(CP_ACP, 0, c, strlen(c), m_wchar, len);
    m_wchar[len] = '';
    return m_wchar;
}
char* WcharToChar(const wchar_t* wp)
{
    char *m_char;
    //映射一个unicode字符串到一个多字节字符串
    int len = WideCharToMultiByte(CP_ACP, 0, wp, wcslen(wp), NULL, 0, NULL, NULL);
    m_char = new char[len + 1];
    WideCharToMultiByte(CP_ACP, 0, wp, wcslen(wp), m_char, len, NULL, NULL);
    m_char[len] = '';
    //printf("my char %s
", 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 = 0;
    
    while (file) {
        string line;
        getline(file, line);
        cout << line << endl;
        if (line == "")break;
        if (i == 0) {
            tempStr = line;
            tempStr += "第一行加这个
";
        }
        else {
            tempStr += line;
            tempStr += "其他行
";
        }
        i++;
    }
    ofstream outfile(name, ios::out | ios::trunc);
    outfile << tempStr << endl;
}

int main()
{
    int j = 0;
    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(-1);//搜索失败
    }
    cout << "路径名:" << Path << endl;

    do {
        //必须加这句,不然会加载.和..的文件而加载不了图片,
        if (pNextInfo.cFileName[0] == '.')continue;
        string name = pNextInfo.cFileName;
        cout << name << endl;
        operate(".\files\"+name);
        j++;
    } while (FindNextFile(hFile, &pNextInfo));
    system("pause");
    return 0;
    
}

其中 files 为 文件夹名称。

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

原文地址:https://www.cnblogs.com/farewell-farewell/p/7197644.html