如何将.txt文件的内容复制到char数组中?

时间:2016-05-06 20:54:50

标签: c file-io

void my_read (char* path, int bytes_number, int sockfd)
{
    FILE* fp;
    int n;
    char buffer[BUFFER_SIZE];
    if (bytes_number > 1000 || bytes_number < 0)
    {
        write (sockfd, "Failure", strlen("Failure"));
        return;
    }
    fp = fopen(path, "r");

我需要一个命令来获取第一个bytes_number chars并将它们放入数组中。

fscanf(fp, "%s", buffer);此命令将复制整个txt

如果我在"%.*s", int k内使用fscanf缓冲区,则输出到数组是错误的。一些奇怪的输出而不是.txt

中的第一个k字符

1 个答案:

答案 0 :(得分:0)

以下代码可能会有所帮助:

// Get the file size
fseek(fp,0,SEEK_END);
size = ftell(fp);
fseek(fp,0,SEEK_SET);

// Read content
read = fread(buffer,1,size,fp);