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

标签 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 字符 并将它们放入数组中。

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

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

最佳答案

也许下面的代码可能会有所帮助:

// 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);

关于c - 如何将 .txt 文件的内容复制到 char 数组中?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37081259/

相关文章:

c - 编译 C 程序时出错

c - 关于C中字符串数组的qsort

c - C 中字符缓冲区的最大大小?

c - 使用 C 使用 strftime() 获取缩写时区

c - 根指针移动到指向二叉搜索树中插入的单词

PHP file_get_contents 超时 "local file"(NFS/挂载)

python - 文本文件无法在输出窗口中打开。Python(Pycharm IDE)

c - 整数除法的行为是什么?

c - 在文件目录字符串中放置空格

我可以将同一个文件指针分配给第二个文件吗?