Hướng dẫn read binary file c++ - đọc tệp nhị phân c ++

Chuyển đến nội phân

Trình Duyệt nào Không CNn Đan Hỗ trợ nữa.

Hãy nâng cấp lênn microsoft ed

Cách để: Đọc từ các tệp nhị phân trong Visual Basic

  • Bài viết
  • 15/09/2021
  • 2 Phú

Trong bài viết nào

Đối tượng My.Computer.FileSystem cung cấp phương thức ReadAllBytes để đọc từ các tệp nhị phân.

Để đọc từ một tệp nhị phân

  • Sử dụng phương thức ReadAllBytes, trả về nội dung của tệp dưới dạng mảng byte. Ví dụ này đọc từ tệp

    ' This method does not trap for exceptions. If an exception is 
    ' encountered opening the file to be copied or writing to the 
    ' destination location, then the exception will be thrown to 
    ' the requestor.
    Public Sub CopyBinaryFile(ByVal path As String,
                              ByVal copyPath As String,
                              ByVal bufferSize As Integer,
                              ByVal overwrite As Boolean)
    
        Dim inputFile = IO.File.Open(path, IO.FileMode.Open)
    
        If overwrite AndAlso My.Computer.FileSystem.FileExists(copyPath) Then
            My.Computer.FileSystem.DeleteFile(copyPath)
        End If
    
        ' Adjust array length for VB array declaration.
        Dim bytes = New Byte(bufferSize - 1) {}
    
        While inputFile.Read(bytes, 0, bufferSize) > 0
            My.Computer.FileSystem.WriteAllBytes(copyPath, bytes, True)
        End While
    
        inputFile.Close()
    End Sub
    
    1.

    Dim bytes = My.Computer.FileSystem.ReadAllBytes(
                  "C:/Documents and Settings/selfportrait.jpg")
    PictureBox1.Image = Image.FromStream(New IO.MemoryStream(bytes))
    
  • Đối với các tệp nhị phân lớn, bạn có thể sử dụng phương thức đọc của đối tượng FileStream để đọc từ tệp chỉ một lượng được chỉ định tại một thời điểm. Sau đó, bạn có thể giới hạn số lượng tệp được tải vào bộ nhớ cho mỗi thao tác đọc. Ví dụ mã sau đây sao chép một tệp và cho phép người gọi chỉ định số lượng tệp được đọc vào bộ nhớ trên mỗi thao tác đọc.

    ' This method does not trap for exceptions. If an exception is 
    ' encountered opening the file to be copied or writing to the 
    ' destination location, then the exception will be thrown to 
    ' the requestor.
    Public Sub CopyBinaryFile(ByVal path As String,
                              ByVal copyPath As String,
                              ByVal bufferSize As Integer,
                              ByVal overwrite As Boolean)
    
        Dim inputFile = IO.File.Open(path, IO.FileMode.Open)
    
        If overwrite AndAlso My.Computer.FileSystem.FileExists(copyPath) Then
            My.Computer.FileSystem.DeleteFile(copyPath)
        End If
    
        ' Adjust array length for VB array declaration.
        Dim bytes = New Byte(bufferSize - 1) {}
    
        While inputFile.Read(bytes, 0, bufferSize) > 0
            My.Computer.FileSystem.WriteAllBytes(copyPath, bytes, True)
        End While
    
        inputFile.Close()
    End Sub
    

Lập trình mạnh mẽ

Các điều kiện sau đây có thể khiến một ngoại lệ bị ném:

  • Đường dẫn không hợp lệ vì một trong những lý do sau: đó là chuỗi không có độ dài, nó chỉ chứa không gian trắng, nó chứa các ký tự không hợp lệ hoặc đó là đường dẫn thiết bị (ArgentSexception).

  • Đường dẫn không hợp lệ vì nó là

    ' This method does not trap for exceptions. If an exception is 
    ' encountered opening the file to be copied or writing to the 
    ' destination location, then the exception will be thrown to 
    ' the requestor.
    Public Sub CopyBinaryFile(ByVal path As String,
                              ByVal copyPath As String,
                              ByVal bufferSize As Integer,
                              ByVal overwrite As Boolean)
    
        Dim inputFile = IO.File.Open(path, IO.FileMode.Open)
    
        If overwrite AndAlso My.Computer.FileSystem.FileExists(copyPath) Then
            My.Computer.FileSystem.DeleteFile(copyPath)
        End If
    
        ' Adjust array length for VB array declaration.
        Dim bytes = New Byte(bufferSize - 1) {}
    
        While inputFile.Read(bytes, 0, bufferSize) > 0
            My.Computer.FileSystem.WriteAllBytes(copyPath, bytes, True)
        End While
    
        inputFile.Close()
    End Sub
    
    2 (archarchNulLexcepce).

  • Tệp không tồn tại (FilenotFoundException).

  • Tệp được sử dụng bởi một quy trình khác hoặc xảy ra lỗi I/O (IOException).

  • Đường dẫn vượt quá độ dài tối đa do hệ thống xác định (PathToolongException).

  • Tên tệp hoặc thư mục trong đường dẫn chứa dấu hai chấm (:) hoặc ở định dạng không hợp lệ (NotSupportedException).

  • Không có đủ bộ nhớ để viết chuỗi vào bộ đệm (outofmemoryException).

  • Người dùng thiếu các quyền cần thiết để xem đường dẫn (SecurityException).

Không đưa ra quyết định về nội dung của tệp dựa trên tên của tệp. Ví dụ: File Form1.vb có thể không phải là tệp nguồn trực quan.

Xác minh tất cả các đầu vào trước khi sử dụng dữ liệu trong ứng dụng của bạn. Nội dung của tệp có thể không phải là những gì được mong đợi và các phương pháp để đọc từ tệp có thể thất bại.

Xem thêm

  • Readallbytes
  • Writeallbytes
  • Đọc từ các tập tin
  • Cách để: Đọc từ các tệp văn bản có nhiều định dạng
  • Lưu trữ dữ liệu đến và đọc từ bảng tạm

Phản HồI

Gửi và xem ý kiến ​​ph

Đọc và viết các tệp nhị phân khá giống với bất kỳ tệp nào khác, sự khác biệt duy nhất là cách bạn mở nó:

unsigned char buffer[10];
FILE *ptr;

ptr = fopen("test.bin","rb");  // r for read, b for binary

fread(buffer,sizeof(buffer),1,ptr); // read 10 bytes to our buffer

Bạn đã nói rằng bạn có thể đọc nó, nhưng nó không xuất hiện chính xác ... Hãy nhớ rằng khi bạn "xuất" dữ liệu này, bạn không đọc ASCII, vì vậy nó không giống như in chuỗi vào màn hình:

for(int i = 0; i<10; i++)
    printf("%u ", buffer[i]); // prints a series of bytes

Viết vào một tệp là khá giống nhau, ngoại trừ bạn đang sử dụng

' This method does not trap for exceptions. If an exception is 
' encountered opening the file to be copied or writing to the 
' destination location, then the exception will be thrown to 
' the requestor.
Public Sub CopyBinaryFile(ByVal path As String,
                          ByVal copyPath As String,
                          ByVal bufferSize As Integer,
                          ByVal overwrite As Boolean)

    Dim inputFile = IO.File.Open(path, IO.FileMode.Open)

    If overwrite AndAlso My.Computer.FileSystem.FileExists(copyPath) Then
        My.Computer.FileSystem.DeleteFile(copyPath)
    End If

    ' Adjust array length for VB array declaration.
    Dim bytes = New Byte(bufferSize - 1) {}

    While inputFile.Read(bytes, 0, bufferSize) > 0
        My.Computer.FileSystem.WriteAllBytes(copyPath, bytes, True)
    End While

    inputFile.Close()
End Sub
3 thay vì
' This method does not trap for exceptions. If an exception is 
' encountered opening the file to be copied or writing to the 
' destination location, then the exception will be thrown to 
' the requestor.
Public Sub CopyBinaryFile(ByVal path As String,
                          ByVal copyPath As String,
                          ByVal bufferSize As Integer,
                          ByVal overwrite As Boolean)

    Dim inputFile = IO.File.Open(path, IO.FileMode.Open)

    If overwrite AndAlso My.Computer.FileSystem.FileExists(copyPath) Then
        My.Computer.FileSystem.DeleteFile(copyPath)
    End If

    ' Adjust array length for VB array declaration.
    Dim bytes = New Byte(bufferSize - 1) {}

    While inputFile.Read(bytes, 0, bufferSize) > 0
        My.Computer.FileSystem.WriteAllBytes(copyPath, bytes, True)
    End While

    inputFile.Close()
End Sub
4:

FILE *write_ptr;

write_ptr = fopen("test.bin","wb");  // w for write, b for binary

fwrite(buffer,sizeof(buffer),1,write_ptr); // write 10 bytes from our buffer

Vì chúng ta đang nói về Linux .. có một cách dễ dàng để kiểm tra tỉnh táo. Cài đặt

' This method does not trap for exceptions. If an exception is 
' encountered opening the file to be copied or writing to the 
' destination location, then the exception will be thrown to 
' the requestor.
Public Sub CopyBinaryFile(ByVal path As String,
                          ByVal copyPath As String,
                          ByVal bufferSize As Integer,
                          ByVal overwrite As Boolean)

    Dim inputFile = IO.File.Open(path, IO.FileMode.Open)

    If overwrite AndAlso My.Computer.FileSystem.FileExists(copyPath) Then
        My.Computer.FileSystem.DeleteFile(copyPath)
    End If

    ' Adjust array length for VB array declaration.
    Dim bytes = New Byte(bufferSize - 1) {}

    While inputFile.Read(bytes, 0, bufferSize) > 0
        My.Computer.FileSystem.WriteAllBytes(copyPath, bytes, True)
    End While

    inputFile.Close()
End Sub
5 trên hệ thống của bạn (nếu nó chưa có ở đó) và đổ tệp của bạn:

mike@mike-VirtualBox:~/C$ hexdump test.bin
0000000 457f 464c 0102 0001 0000 0000 0000 0000
0000010 0001 003e 0001 0000 0000 0000 0000 0000
...

Bây giờ so sánh điều đó với đầu ra của bạn:

mike@mike-VirtualBox:~/C$ ./a.out 
127 69 76 70 2 1 1 0 0 0

Hmm, có thể thay đổi

' This method does not trap for exceptions. If an exception is 
' encountered opening the file to be copied or writing to the 
' destination location, then the exception will be thrown to 
' the requestor.
Public Sub CopyBinaryFile(ByVal path As String,
                          ByVal copyPath As String,
                          ByVal bufferSize As Integer,
                          ByVal overwrite As Boolean)

    Dim inputFile = IO.File.Open(path, IO.FileMode.Open)

    If overwrite AndAlso My.Computer.FileSystem.FileExists(copyPath) Then
        My.Computer.FileSystem.DeleteFile(copyPath)
    End If

    ' Adjust array length for VB array declaration.
    Dim bytes = New Byte(bufferSize - 1) {}

    While inputFile.Read(bytes, 0, bufferSize) > 0
        My.Computer.FileSystem.WriteAllBytes(copyPath, bytes, True)
    End While

    inputFile.Close()
End Sub
6 thành
' This method does not trap for exceptions. If an exception is 
' encountered opening the file to be copied or writing to the 
' destination location, then the exception will be thrown to 
' the requestor.
Public Sub CopyBinaryFile(ByVal path As String,
                          ByVal copyPath As String,
                          ByVal bufferSize As Integer,
                          ByVal overwrite As Boolean)

    Dim inputFile = IO.File.Open(path, IO.FileMode.Open)

    If overwrite AndAlso My.Computer.FileSystem.FileExists(copyPath) Then
        My.Computer.FileSystem.DeleteFile(copyPath)
    End If

    ' Adjust array length for VB array declaration.
    Dim bytes = New Byte(bufferSize - 1) {}

    While inputFile.Read(bytes, 0, bufferSize) > 0
        My.Computer.FileSystem.WriteAllBytes(copyPath, bytes, True)
    End While

    inputFile.Close()
End Sub
7 để làm cho điều này rõ ràng hơn một chút:

mike@mike-VirtualBox:~/C$ ./a.out 
7F 45 4C 46 2 1 1 0 0 0

Này, nhìn xem! Dữ liệu khớp với ngay bây giờ*. Tuyệt vời, chúng ta phải đọc tệp nhị phân một cách chính xác!

*Lưu ý các byte chỉ được hoán đổi trên đầu ra nhưng dữ liệu đó là chính xác, bạn có thể điều chỉnh cho loại điều này