[C / C ++] [File, Directory files, directories]

Creative Commons License Copyright: Attribution, allow others to create paper-based, and must distribute paper (based on the original license agreement with the same license Creative Commons )

Easy Code Scanning folders

+ Compiler environment results Screenshot
Here Insert Picture Description

#pragma warning(disable : 4530)

#include <iostream>
#include <string.h>
#include <io.h>
using namespace std;

#define ArrLnt 200

void fnFind(char *fileName)
{
    char fileNameNew[ArrLnt];
    intptr_t findHandle;
    _finddata_t findData;

    strcpy(fileNameNew, fileName);
    strcat(fileNameNew, "\\*.*");
    findHandle = _findfirst(fileNameNew, &findData);

    if (findHandle == -1)
        return;

    static char indent[ArrLnt];
    strcat(indent, "  ");

    do
    {
        cout << indent << "|";
        if (findData.attrib == _A_SUBDIR)
        {
            strcpy(fileNameNew, fileName);
            strcat(fileNameNew, "\\");
            strcat(fileNameNew, findData.name);

            cout << fileNameNew << endl;

            if (strcmp(findData.name, ".") == 0 || strcmp(findData.name, "..") == 0)
                continue;
            fnFind(fileNameNew);
            indent[strlen(indent) - 2] = '\0';
        }
        else
        {
            cout << findData.name << endl;
        }
    } while (_findnext(findHandle, &findData) == 0);

    _findclose(findHandle);
}

int main()
{
    char fileName[ArrLnt] = "C:\\Users\\Administrator\\Desktop\\c\\A";

    cout << "\n --- start --- \n"
         << endl;
    fnFind(fileName);
    cout << "\n --- end --- \n"
         << endl;

    return 0;
}

Error: Could not the "std :: string" is converted to "char *"

The C ++ std :: string is converted to char *, must () method takes a string through a C-style c_str string object.

If you want high efficiency, or the use of [](may exceed the border) to visit if you want good stability, it is best to use at()to access.

_finddata_t、_findfirst、_findnext和_findclose

#include <io.h>

_finddata_t file information structure

struct _finddata_t
{
    unsigned attrib;    // attribute
    time_t time_create; // # define time_t long
    time_t time_access; //
    time_t time_write;  //
    _fsize_t size;      // # define _fsize_t unsigned long
    char name[260];     //
};

file attribute file attribute

cout
    << _A_NORMAL << endl // 正常 0
    << _A_RDONLY << endl // 只读 1
    << _A_HIDDEN << endl //隐藏 2
    << _A_SYSTEM << endl //系统 4
    << _A_SUBDIR << endl //子文件夹 16
    << _A_ARCH << endl   //存档 32 archived file 
    << endl;

These are defined in the header file macro is an unsigned integer.

_findfirst

long _findfirst(const char *_FileName, struct _finddata_t *_FindData);

  • The first parameter is the file name can be used *.*to find all files can also be used *.cppto locate the .cppfile.
  • The second parameter is the _finddata_tstructure pointer. If the search is successful, return the file handle, if fails, returns -1.
char *fileName = "C:";
intptr_t findHandle;
_finddata_t findData;
_findfirst(fileName, findData);

_findnext

intptr_t _findfirst64i32(const char *_FileName, _finddata64i32_t *_FindData)
The first argument is a file handle, the second parameter is _finddata_t structure pointer. If the search is successful, it returns 0, failure to return -1.

intptr_t findHandle;
_finddata_t findData;
_findnext(findHandle, &findData);

typedef long long intptr_t;

_findclose

int __cdecl _findclose(intptr_t _FindHandle);Only one parameter, the file handle. Close returns 0 if successful, -1 failure.

intptr_t findHandle;
_findclose(findHandle);

#pragma warning(disable : 4530)

#include <iostream>
#include <vector>
#include <string>
#include <cstring> // for strcat()

#include <stdlib.h>
#include <io.h>
using namespace std;

#define PathLength 200
vector<char *> getFilesList(char *dir)
{
    vector<char *> allPath;

    char dirNew[PathLength];

    strcpy(dirNew, dir);
    strcat(dirNew, "\\*.*"); // 在目录后面加上"\\*.*"进行第一次搜索

    cout << dirNew << endl;
    system("pause");

    intptr_t handle;
    _finddata_t findData;

    if ((handle = _findfirst(dirNew, &findData)) == -1)
    { // 检查是否成功
        cout << "can not found the file ... " << endl;
        return allPath;
    }

    do
    {
        if (findData.attrib & _A_SUBDIR) // 是否含有子目录
        {
            // 若该子目录为"."或"..",则进行下一次循环,否则输出子目录名,并进入下一次搜索
            if (strcmp(findData.name, ".") == 0 || strcmp(findData.name, "..") == 0)
                continue;

            cout << findData.name << "\t<dir>\n";
            // 在目录后面加上"\\"和搜索到的目录名进行下一次搜索
            strcpy(dirNew, dir);
            strcat(dirNew, "\\");
            strcat(dirNew, findData.name);

            vector<char *> tempPath = getFilesList(dirNew);
            allPath.insert(allPath.end(), tempPath.begin(), tempPath.end());
        }
        else //不是子目录,即是文件,则输出文件名和文件的大小
        {
            char *filePath = new char[PathLength];
            strcpy(filePath, dir);
            strcat(filePath, "\\");
            strcat(filePath, findData.name);

            allPath.push_back(filePath);
            cout << filePath << "\t" << findData.size << " bytes.\n";
        }
    } while (_findnext(handle, &findData) == 0);

    _findclose(handle); // 关闭搜索句柄
    return allPath;
}

int main()
{
    char dir[PathLength] = "C:\\Users\\Administrator\\Desktop\\c";
    // cout << "\nEnter a directory: ";
    // cin >> dir;

    cout << "\nOutput all file paths :" << endl;

    getFilesList(dir);
    // for (auto path : getFilesList(dir))
    //     cout << path << endl;

    return 0;
}

Directory catalog

unistd.h

unistd.h below the windows is not - for the child, his mother - CSDN blog

  • Programs written under Linux is the default include this header file does not need to include this particular file.
  • Without this stuff below the windows, so the windows need to write the following about this header file
    self a unistd.h, file content
#ifndef _UNISTD_H
#define _UNISTD_H
#include <io.h>
#include <process.h>
#endif /* _UNISTD_H */

And it is equivalent to windows.h under windows.

chdir、getcwd

#include <stdio.h>
#include <direct.h>

int main(int argc, char *argv[])
{
    if (chdir(argv[1]) == -1)
    { // 将当前工作目录切换到 argv[1](从命令行传进来的路径)
        perror("chdir");
        return -1;
    }
    printf("\n Current Working Directory : %s!\n", getcwd(NULL, 0));

    return 0;
}

getcwd

Get Current Working Directory

#include <stdio.h>
#include <direct.h>
int main()
{
    printf("\nCurrent Working Directory : %s\n", getcwd(NULL, 0));
    return 0;
}

fopen

FILE *fopen(const char *filename, const char *mode);
fopen - C++ Reference

mode

C string containing a file access mode.

mode
r read: Open file for input operations. The file must exist.
w write: Create an empty file for output operations. If a file with the same name already exists, its contents are discarded and the file is treated as a new empty file.
a append: Open file for output at the end of a file. Output operations always write data at the end of the file, expanding it. Repositioning operations (fseek, fsetpos, rewind) are ignored. The file is created if it does not exist.
r+ read/update: Open a file for update (both for input and output). The file must exist.
w+ write/update: Create an empty file and open it for update (both for input and output). If a file with the same name already exists its contents are discarded and the file is treated as a new empty file.
a+ append/update: Open a file for update (both for input and output) with all output operations writing data at the end of the file. Repositioning operations (fseek, fsetpos, rewind) affects the next input operations, but output operations move the position back to the end of file. The file is created if it does not exist.

fscanf

fprintf

fclose

#include<stdio.h>
int main(){
    
    FILE *fp=fopen("in.txt","r");
    char cr;
    fscanf(fp,"%c",&cr);
    fclose(fp);
    
    fp=fopen("out.txt","w");
    fprintf(fp,"%c",cr);
    fclose(fp);
    
    return 0;
}

freopen

FILE * freopen ( const char * filename, const char * mode, FILE * stream );

  • FILE * stream 通常使用标准流文件(stdin/stdout/stderr)
freopen("in.txt","r",stdin); //输入重定向,输入数据将从in.txt文件中读取
freopen("out.txt","w",stdout); //输出重定向,输出数据将保存在out.txt文件中

freopen("CON","r",stdin);   //从控制台读入
freopen("CON","w",stdout);//从控制台输出

fclose(stdin);//关闭文件
fclose(stdout);//关闭文件

把预定义的标准流文件定向到由 filename 指定的文件中。
标准流文件具体是指 stdin、stdout和stderr。其中

  • stdin是标准输入流,默认为键盘
  • stdout是标准输出流,默认为屏幕
  • stderr是标准错误流,默认为屏幕。
    通过调用freopen,就可以修改标准流文件的默认值,实现重定向。

若要恢复句柄,可以重新打开标准控制台设备文件,只是这个设备文件的名字是与操作系统相关的。

DOS/Windows
freopen("CON", "r", stdin);

Linux
freopen("/dev/console", "r", stdin);

system


#include <stdio.h>
#include <stdlib.h>
#include <windows.h>

int main()
{
    system("color 02");
    system("calc");
    system("title shotdown");
    // system("pause");
    printf("ha\n");
    Sleep(1000);
    system("cls");
    system("C:\\Users\\Administrator\\Desktop\\c\\c.txt");
    return 0;
}

/、…、. 根目录、父目录、当前目录

/ 根目录
…、…/ 上一层目录(父目录)
.、./ 当前目录

文件路径中 /、\ 斜杠、反斜杠区别


  • \ Generally is a local directory,C:\windows
  • / Mainly represents the remote computer or network address,https://www.baidu.com

U disk

C with the file pointer action file.
** based on C ++ file streams (i.e., non-standard input and output) file operations **.

Programs intended function: self-replicating, start (whether implant registry) after a short wait to read the file type, delete or encrypt files

Guess you like

Origin blog.csdn.net/qq_35689096/article/details/92800036