【小沐学C++】C++17实现文件读写

1、C library function

https://docs.microsoft.com/en-us/cpp/c-runtime-library/stream-i-o?view=msvc-170
文件打开和关闭。

#include <stdio.h>

FILE *stream, *stream2;

int main( void )
{
   int numclosed;

   // Open for read (will fail if file "crt_fopen.c" does not exist)
   if( (stream  = fopen( "crt_fopen.c", "r" )) == NULL ) // C4996
   // Note: fopen is deprecated; consider using fopen_s instead
      printf( "The file 'crt_fopen.c' was not opened\n" );
   else
      printf( "The file 'crt_fopen.c' was opened\n" );

   // Open for write
   if( (stream2 = fopen( "data2", "w+" )) == NULL ) // C4996
      printf( "The file 'data2' was not opened\n" );
   else
      printf( "The file 'data2' was opened\n" );

   // Close stream if it is not NULL
   if( stream)
   {
      if ( fclose( stream ) )
      {
         printf( "The file 'crt_fopen.c' was not closed\n" );
      }
   }

   // All other files are closed:
   numclosed = _fcloseall( );
   printf( "Number of files closed by _fcloseall: %u\n", numclosed );
}

多个字符循环读取文件。

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

int main( void )
{
   int  count, total = 0;
   char buffer[100];
   FILE *stream;

   fopen_s( &stream, "crt_feof.txt", "r" );
   if( stream == NULL )
      exit( 1 );

   // Cycle until end of file reached:
   while( !feof( stream ) )
   {
      // Attempt to read in 100 bytes:
      count = fread( buffer, sizeof( char ), 100, stream );
      if( ferror( stream ) )      {
         perror( "Read error" );
         break;
      }

      // Total up actual bytes read
      total += count;
   }
   printf( "Number of bytes read = %d\n", total );
   fclose( stream );
}

单个字符循环读取文件。

#include <stdio.h>

int main () {
   FILE *fp;
   int c;
  
   fp = fopen("file.txt","r");
   while(1) {
      c = fgetc(fp);
      if( feof(fp) ) { 
         break ;
      }
      printf("%c", c);
   }
   fclose(fp);
   
   return(0);
}

2、C++ standard library

https://docs.microsoft.com/en-us/cpp/standard-library/basic-ifstream-class?view=msvc-170

打开方式包括:

  1. ios::in 读文件
  2. ios::out 写文件(直接用的话会丢弃已有数据,隐含为trunc)
  3. ios::binary 二进制方式
  4. ios:app 追加写(要配合out使用,直接写的话会隐含用out)
  5. ios::trunc 覆盖写(要配合out使用)
  6. ios::out|ios::binary 二进制写

2.1 常用文件读写

从文件中读取内容。

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

int main(int argc, char **argv)
{
    ifstream ifs("basic_ifstream_class.txt");
    if (!ifs.bad())
    {
        // Dump the contents of the file to cout.
        cout << ifs.rdbuf();
        ifs.close();
    }
}

单个字符循环读取文件。

// ios::eof example
#include <iostream>     // std::cout
#include <fstream>      // std::ifstream

int main () {

  std::ifstream is("example.txt");   // open file

  char c;
  while (is.get(c))                  // loop getting single characters
    std::cout << c;

  if (is.eof())                      // check for EOF
    std::cout << "[EoF reached]\n";
  else
    std::cout << "[error reading]\n";

  is.close();                        // close file

  return 0;
}

保存字符串到文件中。

#include <fstream>
using namespace std;

int main(int argc, char **argv)
{
    ofstream ofs("ofstream.txt");
    if (!ofs.bad())
    {
        ofs << "Writing to a basic_ofstream object..." << endl;
        ofs.close();
    }
}

保存字符串到文件,然后读取出来。

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

int main(int argc, char **argv)
{
    fstream fs("fstream.txt", ios::in | ios::out | ios::trunc);
    if (!fs.bad())
    {
        // Write to the file.
        fs << "Writing to a basic_fstream object..." << endl;
        fs.close();

        // Dump the contents of the file to cout.
        fs.open("fstream.txt", ios::in);
        cout << fs.rdbuf();
        fs.close();
    }
}

打开和关闭文件。

#include <fstream>
#include <iostream>

int main( )
{
   using namespace std;
   ifstream file;
   // Open and close with a basic_filebuf
   file.rdbuf( )->open( "basic_ofstream_is_open.txt", ios::in );
   file.close( );
   if (file.is_open())
      cout << "it's open" << endl;
   else
      cout << "it's closed" << endl;
}

2.2 一次读取整个文件

  • (1)读取至char*的方式
#include <fstream>

std::ifstream fs;
int length;
fs.open("file.txt");      // open input file
fs.seekg(0, std::ios::end);    // go to the end
length = fs.tellg();           // report location (this is the length)
fs.seekg(0, std::ios::beg);    // go back to the beginning
buffer = new char[length];    // allocate memory for a buffer of appropriate dimension
fs.read(buffer, length);       // read the whole file into the buffer
fs.close();                    // close file handle
  • (2)读取至std::string的方式
#include <string>
#include <fstream>
#include <streambuf>
 
std::ifstream fs("file.txt");
std::string str((std::istreambuf_iterator<char>(fs)),
                 std::istreambuf_iterator<char>());

#include <string>
#include <fstream>
#include <sstream>

std::ifstream fs("file.txt");
std::stringstream buffer;
buffer << fs.rdbuf();
std::string contents(buffer.str());

3、CFile 类(MFC)

CFile 类 - Microsoft 基础类文件类的基类。

  • 写操作1:
CFile cfile;
cfile.Open(_T("Write_File.dat"), CFile::modeCreate | 
   CFile::modeReadWrite);
char pbufWrite[100];
memset(pbufWrite, 'a', sizeof(pbufWrite));
cfile.Write(pbufWrite, 100);         
cfile.Flush();
  • 写操作2:
TCHAR* pstrName = _T("C:\\test\\SetPath_File.dat");

// open a file
HANDLE hFile = ::CreateFile(pstrName, GENERIC_WRITE, FILE_SHARE_READ,
   NULL, CREATE_ALWAYS, 0, NULL);

if (hFile != INVALID_HANDLE_VALUE)
{
   // attach a CFile object to it
   CFile myFile(hFile);

   // At this point, myFile doesn't know the path name for the file
   // it owns because Windows doesn't associate that information
   // with the handle. Any CFileExceptions thrown by this object
   // won't have complete information.

   // Calling SetFilePath() remedies that problem by letting CFile
   // know the name of the file that's associated with the object.

   myFile.SetFilePath(pstrName);

   // write something to the file and flush it immediately
   DWORD dwValue = 1234;
   myFile.Write(&dwValue, sizeof(dwValue));
   myFile.Flush();

   // destroying the CObject here will call ::CloseHandle() on the file
} 
  • 读操作:
CFile cfile;
cfile.Open(_T("Write_File.dat"), CFile::modeCreate | 
   CFile::modeReadWrite);
char pbufWrite[100];
memset(pbufWrite, 'a', sizeof(pbufWrite));
cfile.Write(pbufWrite, 100);         
cfile.Flush();
cfile.SeekToBegin();
char pbufRead[100];
cfile.Read(pbufRead, sizeof(pbufRead));
ASSERT(0 == memcmp(pbufWrite, pbufRead, sizeof(pbufWrite)));

4、CStdioFile类(MFC)

CStdioFile 类:表示由运行时函数 打开的 C 运行时流文件 fopen 。

  • 写操作:
CStdioFile f(stdout);
TCHAR buf[] = _T("test string");

f.WriteString(buf);
  • 读操作:
CStdioFile f(stdin);
TCHAR buf[100];

f.ReadString(buf, 99);

5、Win32 API

File Management (Local File Systems)
Opening a File for Reading or Writing

  • WriteFile
  • WriteFileEx
  • ReadFile
  • ReadFileEx
  • CreateFile

写操作:

#include <windows.h>
#include <tchar.h>
#include <stdio.h>
#include <strsafe.h>

void DisplayError(LPTSTR lpszFunction);

int __cdecl _tmain(int argc, TCHAR *argv[])
{
    HANDLE hFile; 
    char DataBuffer[] = "This is some test data to write to the file.";
    DWORD dwBytesToWrite = (DWORD)strlen(DataBuffer);
    DWORD dwBytesWritten = 0;
    BOOL bErrorFlag = FALSE;

    printf("\n");
    if( argc != 2 )
    {
        printf("Usage Error:\tIncorrect number of arguments\n\n");
        _tprintf(TEXT("%s <file_name>\n"), argv[0]);
        return;
    }

    hFile = CreateFile(argv[1],                // name of the write
                       GENERIC_WRITE,          // open for writing
                       0,                      // do not share
                       NULL,                   // default security
                       CREATE_NEW,             // create new file only
                       FILE_ATTRIBUTE_NORMAL,  // normal file
                       NULL);                  // no attr. template

    if (hFile == INVALID_HANDLE_VALUE) 
    { 
        DisplayError(TEXT("CreateFile"));
        _tprintf(TEXT("Terminal failure: Unable to open file \"%s\" for write.\n"), argv[1]);
        return;
    }

    _tprintf(TEXT("Writing %d bytes to %s.\n"), dwBytesToWrite, argv[1]);

    bErrorFlag = WriteFile( 
                    hFile,           // open file handle
                    DataBuffer,      // start of data to write
                    dwBytesToWrite,  // number of bytes to write
                    &dwBytesWritten, // number of bytes that were written
                    NULL);            // no overlapped structure

    if (FALSE == bErrorFlag)
    {
        DisplayError(TEXT("WriteFile"));
        printf("Terminal failure: Unable to write to file.\n");
    }
    else
    {
        if (dwBytesWritten != dwBytesToWrite)
        {
            // This is an error because a synchronous write that results in
            // success (WriteFile returns TRUE) should write all data as
            // requested. This would not necessarily be the case for
            // asynchronous writes.
            printf("Error: dwBytesWritten != dwBytesToWrite\n");
        }
        else
        {
            _tprintf(TEXT("Wrote %d bytes to %s successfully.\n"), dwBytesWritten, argv[1]);
        }
    }

    CloseHandle(hFile);
}

void DisplayError(LPTSTR lpszFunction) 
// Routine Description:
// Retrieve and output the system error message for the last-error code
{ 
    LPVOID lpMsgBuf;
    LPVOID lpDisplayBuf;
    DWORD dw = GetLastError(); 

    FormatMessage(
        FORMAT_MESSAGE_ALLOCATE_BUFFER | 
        FORMAT_MESSAGE_FROM_SYSTEM |
        FORMAT_MESSAGE_IGNORE_INSERTS,
        NULL,
        dw,
        MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT),
        (LPTSTR) &lpMsgBuf,
        0, 
        NULL );

    lpDisplayBuf = 
        (LPVOID)LocalAlloc( LMEM_ZEROINIT, 
                            ( lstrlen((LPCTSTR)lpMsgBuf)
                              + lstrlen((LPCTSTR)lpszFunction)
                              + 40) // account for format string
                            * sizeof(TCHAR) );
    
    if (FAILED( StringCchPrintf((LPTSTR)lpDisplayBuf, 
                     LocalSize(lpDisplayBuf) / sizeof(TCHAR),
                     TEXT("%s failed with error code %d as follows:\n%s"), 
                     lpszFunction, 
                     dw, 
                     lpMsgBuf)))
    {
        printf("FATAL ERROR: Unable to output error code.\n");
    }
    
    _tprintf(TEXT("ERROR: %s\n"), (LPCTSTR)lpDisplayBuf);

    LocalFree(lpMsgBuf);
    LocalFree(lpDisplayBuf);

读操作:

#include <windows.h>
#include <tchar.h>
#include <stdio.h>
#include <strsafe.h>

#define BUFFERSIZE 5
DWORD g_BytesTransferred = 0;

void DisplayError(LPTSTR lpszFunction);

VOID CALLBACK FileIOCompletionRoutine(
  __in  DWORD dwErrorCode,
  __in  DWORD dwNumberOfBytesTransfered,
  __in  LPOVERLAPPED lpOverlapped
);

VOID CALLBACK FileIOCompletionRoutine(
  __in  DWORD dwErrorCode,
  __in  DWORD dwNumberOfBytesTransfered,
  __in  LPOVERLAPPED lpOverlapped )
 {
  _tprintf(TEXT("Error code:\t%x\n"), dwErrorCode);
  _tprintf(TEXT("Number of bytes:\t%x\n"), dwNumberOfBytesTransfered);
  g_BytesTransferred = dwNumberOfBytesTransfered;
 }

//
// Note: this simplified sample assumes the file to read is an ANSI text file
// only for the purposes of output to the screen. CreateFile and ReadFile
// do not use parameters to differentiate between text and binary file types.
//

int __cdecl _tmain(int argc, TCHAR *argv[])
{
    HANDLE hFile; 
    DWORD  dwBytesRead = 0;
    char   ReadBuffer[BUFFERSIZE] = {0};
    OVERLAPPED ol = {0};

    printf("\n");
    if( argc != 2 )
    {
        printf("Usage Error: Incorrect number of arguments\n\n");
        _tprintf(TEXT("Usage:\n\t%s <text_file_name>\n"), argv[0]);
        return;
    }

    hFile = CreateFile(argv[1],               // file to open
                       GENERIC_READ,          // open for reading
                       FILE_SHARE_READ,       // share for reading
                       NULL,                  // default security
                       OPEN_EXISTING,         // existing file only
                       FILE_ATTRIBUTE_NORMAL | FILE_FLAG_OVERLAPPED, // normal file
                       NULL);                 // no attr. template
 
    if (hFile == INVALID_HANDLE_VALUE) 
    { 
        DisplayError(TEXT("CreateFile"));
        _tprintf(TEXT("Terminal failure: unable to open file \"%s\" for read.\n"), argv[1]);
        return; 
    }

    // Read one character less than the buffer size to save room for
    // the terminating NULL character. 

    if( FALSE == ReadFileEx(hFile, ReadBuffer, BUFFERSIZE-1, &ol, FileIOCompletionRoutine) )
    {
        DisplayError(TEXT("ReadFile"));
        printf("Terminal failure: Unable to read from file.\n GetLastError=%08x\n", GetLastError());
        CloseHandle(hFile);
        return;
    }
    SleepEx(5000, TRUE);
    dwBytesRead = g_BytesTransferred;
    // This is the section of code that assumes the file is ANSI text. 
    // Modify this block for other data types if needed.

    if (dwBytesRead > 0 && dwBytesRead <= BUFFERSIZE-1)
    {
        ReadBuffer[dwBytesRead]='\0'; // NULL character

        _tprintf(TEXT("Data read from %s (%d bytes): \n"), argv[1], dwBytesRead);
        printf("%s\n", ReadBuffer);
    }
    else if (dwBytesRead == 0)
    {
        _tprintf(TEXT("No data read from file %s\n"), argv[1]);
    }
    else
    {
        printf("\n ** Unexpected value for dwBytesRead ** \n");
    }

    // It is always good practice to close the open file handles even though
    // the app will exit here and clean up open handles anyway.
    
    CloseHandle(hFile);
}

void DisplayError(LPTSTR lpszFunction) 
// Routine Description:
// Retrieve and output the system error message for the last-error code
{ 
    LPVOID lpMsgBuf;
    LPVOID lpDisplayBuf;
    DWORD dw = GetLastError(); 

    FormatMessage(
        FORMAT_MESSAGE_ALLOCATE_BUFFER | 
        FORMAT_MESSAGE_FROM_SYSTEM |
        FORMAT_MESSAGE_IGNORE_INSERTS,
        NULL,
        dw,
        MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT),
        (LPTSTR) &lpMsgBuf,
        0, 
        NULL );

    lpDisplayBuf = 
        (LPVOID)LocalAlloc( LMEM_ZEROINIT, 
                            ( lstrlen((LPCTSTR)lpMsgBuf)
                              + lstrlen((LPCTSTR)lpszFunction)
                              + 40) // account for format string
                            * sizeof(TCHAR) );
    
    if (FAILED( StringCchPrintf((LPTSTR)lpDisplayBuf, 
                     LocalSize(lpDisplayBuf) / sizeof(TCHAR),
                     TEXT("%s failed with error code %d as follows:\n%s"), 
                     lpszFunction, 
                     dw, 
                     lpMsgBuf)))
    {
        printf("FATAL ERROR: Unable to output error code.\n");
    }
    
    _tprintf(TEXT("ERROR: %s\n"), (LPCTSTR)lpDisplayBuf);

    LocalFree(lpMsgBuf);
    LocalFree(lpDisplayBuf);
}

后续

如果你觉得这些文字有一点点用处,可以给作者点个赞;╮( ̄▽ ̄)╭
如果你感觉作者写的不咋地//(ㄒoㄒ)//,就在评论处留言,作者继续改进。o_O???
谢谢各位小伙伴们啦( ´ ▽ ‘)ノ ( ´ ▽ ` )っ!!!

  • 9
    点赞
  • 9
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
C++实现文件的分段读写可以通过以下骤进行: 1. 打开文件:使用C++文件流对象,如`std::ifstream`和`std::ofstream`,打开需要读取或写入的文件。 2. 确定文件大小:可以使用文件流对象的`seekg`和`tellg`函数来确定文件的大小。`seekg`函数用于将文件指针移动到指定位置,`tellg`函数用于获取当前文件指针的位置。 3. 分段读取:根据需要设置每次读取的分段大小,可以使用`read`函数从文件中读取指定大小的数据块。读取的数据可以存储在缓冲区中供后续处理。 4. 分段写入:根据需要设置每次写入的分段大小,可以使用`write`函数将数据块写入文件中。写入的数据可以从缓冲区中获取。 5. 关闭文件:在读取或写入完成后,使用文件流对象的`close`函数关闭文件。 下面是一个示例代码,演示了如何实现文件的分段读写: ```cpp #include <iostream> #include <fstream> void splitFile(const std::string& inputFile, const std::string& outputFile, int segmentSize) { std::ifstream inFile(inputFile, std::ios::binary); std::ofstream outFile(outputFile, std::ios::binary); if (!inFile || !outFile) { std::cout << "Failed to open file!" << std::endl; return; } // 获取文件大小 inFile.seekg(0, std::ios::end); std::streampos fileSize = inFile.tellg(); inFile.seekg(0, std::ios::beg); // 分段读取和写入 char* buffer = new char[segmentSize]; std::streampos bytesRead = 0; while (bytesRead < fileSize) { int bytesToRead = (fileSize - bytesRead < segmentSize) ? (fileSize - bytesRead) : segmentSize; inFile.read(buffer, bytesToRead); outFile.write(buffer, bytesToRead); bytesRead += bytesToRead; } delete[] buffer; inFile.close(); outFile.close(); std::cout << "File split successfully!" << std::endl; } int main() { std::string inputFile = "input.txt"; std::string outputFile = "output.txt"; int segmentSize = 1024; // 每次读取或写入的分段大小 splitFile(inputFile, outputFile, segmentSize); return 0; } ``` 请注意,以上示例代码仅演示了如何实现文件的分段读写,并未处理异常情况和错误检查。在实际应用中,需要根据具体需求进行适当的错误处理和异常处理。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值