简体   繁体   中英

Binary Reading from and Writing to a File in C

I need some help writing a program in C to reading and writing binary values from and to a file. For this program I do not need the entire contents of the file (2048 bytes) read in, only the first 30 halfwords.

I do know how to write a program to do this for text files, but am new to binary. Do I need to allocate memory like for text files? Would using a buffer be helpful? Are the commands similar or different to fprintf, sscanf, and other syntax things?

this example should work

#define FILE "file path"
#define LEN 30
int main()
{
    int read;
    char *buffer;
    HANDLE hFile = CreateFile(FILE, GENERIC_READ, FILE_SHARE_READ, NULL, OPEN_EXISTING, 
                              FILE_ATTRIBUTE_NORMAL, NULL);
    if(hFile == INVALID_HANDLE_VALUE){
        printf("[-] CreateFile() failed.\n");
        return 0;}
    buffer = (char*)malloc(LEN);
    ReadFile(hFile, buffer, LEN, &read, NULL);
}

you read the file with no special flags. you mentioned you only need the first 30 halfwords which are obviously the first 30 bytes. ReadFile() has the nNumberOfBytesToRead parameter, so all you need to pass 30. If you want you could try to read an .exe file and print what you got. it should start with MZ and "this program cannot be run in dos mode" (you'd need to read more than 30 bytes in order to see all of it). Some NULL bytes wouldn't let you simply print it so you should try that way

int PrintBuffer(char *buffer)
{
    int written;
    HANDLE out = GetStdHandle(STD_OUTPUT_HANDLE);
    WriteFile(out, buffer, LEN, &written, NULL);
    CloseHandle(out);
}

edit : a version with no winapi

#define PATH "file path"
#define LEN 30
#define HWORD 1
int main()
{
    int i = 0;
    char *buffer = (char*)malloc(LEN);
    FILE *f = fopen(PATH, "rb");

    if(!f) printf("[-] fopen() failed.\n");
    else printf("[+] fopen() succeeded.\n");

    if(fread(buffer, HWORD, LEN, f) != LEN) printf("[-] fread() failed.\n");
    else printf("[+] fread() succeeded.\n");

and now printing the data without the NULL bytes cutting the output too early

    for(i = 0; i < LEN; i++) printf("%c", buffer[i]);
}

fread() reads "elements" from a file has the following parameters:
1. the buffer which will receive the read data.
2. the size of each element in bytes. Half word is a byte, so the size is 1.
3. the number of elements you want to read. in this case 30. 4. the FILE* you used for fopen() .

the return value is the amount of elements successfully read, it should be 30.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM