简体   繁体   中英

Copying all file contents into a char array with fread

I'm trying to copy the contents of a file, specifically a PDF file into a character array so that I can send it over the network.

I'm using the fopen with fread for this.

//Get the file path
getFilePath();
//Open the file
fopen_s(&fp, filePath, "r");
fseek(fp, 0, SEEK_END);
size = ftell(fp);
rewind(fp);
//allocate memory
buffer = (char*)malloc(sizeof(char)*size);

int charsTransferred = fread(buffer, 1, size, fp);

fclose(fp);
free(buffer);

I have charsTransferred to see how many characters were transferred over by fread. Using size I can tell how many characters should have been moved over, but obviously I'm not getting that many back. Does anyone know what the issue here could be?

There may be a problem in the part of your code you didn't show.

This works:

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

void main()
{
  FILE *fp;

  if (fopen_s(&fp, "somepdfile.pdf", "rb"))
  {
    printf("Failed to open file\n");
    exit(1);
  }

  fseek(fp, 0, SEEK_END);
  int size = ftell(fp);
  rewind(fp);

  char *buffer = (char*)malloc(sizeof(char)*size);
  if (!buffer)
  {
    printf("Failed to malloc\n");
    exit(1);
  }

  int charsTransferred = fread(buffer, 1, size, fp);
  printf("charsTransferred = %d, size = %d\n", charsTransferred, size);

  fclose(fp);
  free(buffer);
}

Firstly you need to open in binary mode if a PDF, which I believe is a binary format. Then the seek end / ftell method tends to fail for very large files, as well as for text files (which have suppressed characters physically on the disk). There isn't a pure ANSI C way of statting a file, but the function stat() is widely avialable, and gives you file size.

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