简体   繁体   English

使用fread将所有文件内容复制到char数组中

[英]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. 我正在尝试将文件(尤其是PDF文件)的内容复制到字符数组中,以便可以通过网络发送它。

I'm using the fopen with fread for this. 我为此使用fopen与fread。

//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. 我有charsTransferred来查看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. 首先,如果我认为PDF是二进制格式,则需要以二进制模式打开。 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). 然后,对于非常大的文件以及文本文件(物理上已抑制了磁盘上的字符),seek end / ftell方法往往会失败。 There isn't a pure ANSI C way of statting a file, but the function stat() is widely avialable, and gives you file size. 没有纯粹的ANSI C方式来声明文件,但是stat()函数可广泛使用,并为您提供文件大小。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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