C/C++/Windows/Linux file operations

Article directory

  • C language file operation
    • read file
    • write file
    • Other operations
      • File pointer relocation
      • Get pointer position
      • Get file size
      • Rename file
      • Delete Files
  • C++ file operations
    • read file
    • read file
  • Windows file operations
    • read file
    • write file
    • Other operations
      • Copy files
      • Delete files/directories
      • Determine whether the directory exists
      • Traverse files and directories under a directory
    • ATL read and write files
  • Linux file operations

C language file operation

File access mode string Meaning If the file does not exist, the actual action
“r” Read from the beginning Open failed
“w Overwrite Create new file
“a” Append write Create new File
“r +” Overlay readable and writable Error
“w + ” Overwriting readable and writable Create new file
“a + ” Append readable and writable Create new file
“rb” Read binary from the beginning Open failed
“wb” Overwrite binary Create new file
“ab” Append write binary Create new file
“rb +” Overlay readable and writable binary Error
“wb +” Overlay can Read and write binary Create new file
“ab +” Append read and write binary Create new file

Read file

#include <stdio.h>
int main() {<!-- -->
// 1. Open the file
FILE* fr = fopen("E:\\work\testFile\messfile\23-11-6\1.txt", "r") ; //Open the file for reading
if (fr == NULL) {<!-- --> //file is NULL, then the file fails to open and the program exits.
printf("File cannot be opened! \\
");
return -1;
}
// 2. Read content
char buf[0xFF] = {<!-- --> 0 };
// 2.1 Read in byte blocks
while (!feof(fr)) //Not to the end of the file
{<!-- -->
memset(buf, 0, sizeof(buf));
size_t len = fread(buf, sizeof(char), sizeof(buf), fr); //Read sizeof(char) bytes each time, read sizeof(buf) times, you can also use the fscanf function
printf("buf: %s, len: %d\\
", buf, len);
}

// 2.2 Read by word line. There will be bugs in reading Chinese with this method.
char* str = NULL;
while (!feof(fr))
{<!-- -->
memset(buf, 0, sizeof(buf));
str = fgets(buf, sizeof(buf), fr); //fgets can read up to sizeof(buf) bytes at a time and will stop reading when it encounters a newline character.
printf("buf: %s \\
", buf);
printf("str: %s \\
", str); //Str content is the same as buf content
}

// 2.3 Read by character
char c = 0;
while (c != EOF)
{<!-- -->
c = fgetc(fr); // Get a character
printf("%c", c);
}
printf("\\
");

// 3. Close the file
if (fclose(fr) != 0)
{<!-- -->
printf("File cannot be closed! \\
");
return -1;
}
else
{<!-- -->
printf("File is now closed! \\
");
}
return 0;
}

Write file

#include <stdio.h>
int main(int argc, char* argv[])
{<!-- -->
// 1. Open the file
FILE* fw = fopen("E:\work\testFile\messfile\23-11-6\1.txt", "w") ; //Open the file for reading
if (fw == NULL) {<!-- --> //file is NULL, then the file fails to open and the program exits.
printf("File cannot be opened! \\
");
return -1;
}
// 2. Write content
char buf[128] = {<!-- --> 0 };
\t
// 2.1 Write by data block
char str[] = "Nanpu is sad and sad, and the west phoenix curls up in autumn.";
memcpy(buf, str, strlen(str));
fwrite(buf, strlen(buf) + 1, 1, fw); //Write strlen(buf) bytes each time, once. You can use the fprint function

// 2.2 Write row by row
while (NULL != fgets(buf, sizeof(buf), stdin)) {<!-- -->
printf("Read line with len: %d\\
", strlen(buf));
fputs(buf, fw);
fflush(fw); //Refresh the output buffer
printf("%s", buf);
}
\t

// 2.3 Write by character
char ch = getchar();
while (ch != '$')
{<!-- -->
fputc(ch, fw);
ch = getchar();
}

// 3. Close the file
if (fclose(fw) != 0)
{<!-- -->
printf("File cannot be closed! \\
");
return -1;
}
else
{<!-- -->
printf("File is now closed! \\
");
}
\t
return 0;
}

Other operations

File pointer relocation

int fseek (FILE * stream, long int offset, int origin);

stream: stream
offset: the offset corresponding to the origin position, in bytes
origin: the position of the pointer
#define SEEK_CUR 1 // current position
#define SEEK_END 2 // end
#define SEEK_SET 0 // start

Get pointer position

long int ftell (FILE * stream);

Get file size

long n;
fseek(pf,0,SEEK_END);
n=ftell(pf);

Rename file

int rename ( const char * oldname, const char * newname );

oldname: original name
newname: new name

Delete files

int remove ( const char * filename );

filename: full path to the file

C++ file operations

Open method Meaning
ios::in Read from beginning
ios::out Overwrite write
ios:: ate Put the file pointer to the end
ios::app Append writing
ios::trunc Clear content
ios::binary Open in binary mode

Read file

#include <fstream>
#include <iostream>
using namespace std;
int main(int argc, char* argv[])
{<!-- -->
// 1. Open the file
fstream fr;
fr.open("1.txt", ios::in); //Open the file in read-only mode
if (!fr.is_open())
std::cerr << "cannot open the file!" << endl;
\t
// 2. Read content
char buf[1024] = {<!-- --> 0 };

// 2.1 Read by element
while (fr >> buf)
cout << buf << endl; //Each buf is an element separated by spaces or enter keys

// 2.2 Fetch by row
while (fr.getline(buf, sizeof(buf)))
std::cout << buf << std::endl;

// 2.3 Read by character
char c;
while ((c = fr.get()) != EOF)
std::cout << c;

// 2.4 is often used to read and write binary files, but can also read non-binary files.
fr.read((char*)buf, sizeof(buf)); //Read into buf, read sizeof(buf) bytes
cout << buf;

// 3. Close the file
fr.close();
\t
return 0;
}

Read file

#include <fstream>
#include <iostream>
using namespace std;
int main(int argc, char* argv[])
{<!-- -->
// 1. Open the file
ofstream fw;
fw.open("1.txt", ios::app); //Open the file in append writing mode
if (!fw.is_open())
std::cerr << "cannot open the file!" << endl;
\t
// 2. Write content
// 2.1 Direct writing
fw << "If the heart is broken, Xinfeng wine will be lost, and thousands of sorrows will be spent." << endl;

// 2.2 Commonly used for binary writing, can also be used for ordinary file writing
char buf[1024] = "I am not famous yet and I am not married, so I may not be as good as others.";
fw.write((char*)buf, strlen(buf));
\t

// 3. Close the file
fw.close();
\t
system("pause");
return 0;
}

Windows file operations

Read file

#include <windows.h>
int main(int argc, char* argv[])
{<!-- -->
// 1. Open the file
HANDLE hFile = CreateFile("1.txt", GENERIC_READ, 0, 0, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL);
if (hFile == NULL) {<!-- -->
return -1;
}
// 2. Read the file
char buf[128] = {<!-- --> 0 };
DWORD len = 0;
DWORD dwBytesToRead = GetFileSize(hFile, NULL); //Get the file size
\t
do {<!-- --> //Loop through the file to ensure that the complete file is read out
if (!ReadFile(hFile, buf, dwBytesToRead, & amp;len, NULL)) {<!-- -->
cout << "read file error!" << GetLastError() << endl;
return -1;
}
cout << buf << endl;
dwBytesToRead -= len;
} while (dwBytesToRead > 0);

// 3. Close the file
CloseHandle(hFile);
return 0;
}

Write file

int main(int argc, char* argv[])
{<!-- -->
// 1. Open the file
HANDLE hFile = CreateFile("1.txt", GENERIC_READ | GENERIC_WRITE, 0, 0, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL);
if (hFile == NULL) {<!-- -->
return -1;
}
SetFilePointer(hFile, 0, NULL, FILE_END); //Set the file pointer to the end of the file to implement additional writing
// 2. Write file
char buf[128] = {<!-- --> 0 };
DWORD len = 0;
char str[] = "Lao Ge Yiyi explains boating, red leaves, green mountains and rapids, the sunset is sober and people are far away, the sky is full of wind and rain, and I am descending to the west building.";
memcpy(buf, str, strlen(str));
WriteFile(hFile, buf, strlen(buf), &len, NULL);
FlushFileBuffers(hFile); //Refresh cache
\t
// 3. Close the file
CloseHandle(hFile);

system("pause");
return 0;
}

Other operations

Copy files

CopyFile()

Delete files/directories

deleteFiles(dir)

Determine whether the directory exists

#include<io.h>
if (!GetFileAttributesA(mTempDir.c_str()) & amp; FILE_ATTRIBUTE_DIRECTORY) //Whether the mTempDir directory exists, create the directory if it does not exist
resultFlag = CreateDirectory(mTempDir.c_str(), NULL);

Traverse files and directories under a directory

//File handle, win10 uses long long, win7 uses long.
long long hFile = 0;
//File information
struct _finddata_t fileinfo;
if ((hFile = _findfirst(p.assign(path).append("\*").c_str(), & amp;fileinfo)) != -1) //The first search combination Check whether the directory or file exists
{<!-- -->
do
{<!-- -->
if ((fileinfo.attrib & amp; _A_SUBDIR))//If it is a directory, iterate over it
{<!-- -->
if (strcmp(fileinfo.name, ".") != 0 & amp; & amp; strcmp(fileinfo.name, "..") != 0)
getFiles(p.assign(path).append("\").append(fileinfo.name), files, names);
}
else//If not, add to the list
files.push_back(p.assign(path).append("\").append(fileinfo.name));
} while (_findnext(hFile, & amp;fileinfo) == 0);
_findclose(hFile);
}

ATL read and write files

#include<atlfile.h>
using namespace std;
int main(int argc, char* argv[])
{<!-- -->
CAtlFile file;
file.Create(L"1.txt", GENERIC_WRITE, 0, OPEN_EXISTING);
char buf[128] = "The Big Dipper is horizontal in the sky and the night is dark, and people are worried about leaning on the moon and thinking for no reason.";
file.Seek(0, FILE_END);
file.Write(buf, strlen(buf));
file.Flush();
return 0;
}

Linux file operations

Stay tuned