c - 文件数组和赋值

标签 c arrays file

我有 2 个问题。

我想在 C 中创建一个文件数组。但我不确定是否必须在之前 malloc 大小。我可以只使用 FILE** 文件作为数组吗,还是必须在之前 malloc 它们。如果我必须腾出空间,我需要保留 4 个字节 (x86) 吗?

我有变量“char extra[8] = { 0xAE00AF00B000B100 };”我想将它分配给另一个 char 数组的末尾[24]。有没有一种更快的方法可以做到这一点,而不必手动输入每个值或使用 for 循环。

char extra[8] = { 0xAE00AF00B000B100 };
// index is a random place in the string
name[index] = '\0';
i = 0;
if (index > 16) {
    for (i = 24-index; i < 8; i++) {
        index++;
        name[index] = extra[i];
        }
    }
else {
    name[17] = 0xAE;
    name[18] = 0x00;
    name[19] = 0xAF;
    name[20] = 0x00;
    name[21] = 0xB0;
    name[22] = 0x00;
    name[23] = 0xB1;
    name[24] = 0x00;
}

顺便说一句,我需要添加这些额外的字节。

最佳答案

I want to create an array of files in C. But I'm not sure whether I have to malloc the size before or not.Can I just use FILE** files as an array or do I have to malloc them before. And if I have to make space, do I need to reserve 4 bytes (x86)?

如果您需要一个文件数组,可以使用如下指针数组:

#include <stdio.h>

FILE *array[NB_FILES];

或者,如果 NB_FILES 仅在运行时已知,则可以动态执行此操作。

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

FILE **array = malloc(nb_files * sizeof *array);

I have the variable "char extra[8] = { 0xAE00AF00B000B100 };" and I want to assign it to the end of another char array[24]. Is there a faster way of doing that without having to type in every value by hand or using a for loop.

标准 C 库提供了函数 memcpy,它是许多编译器的内置函数(因此它比 for 循环更快)。

#include <string.h>

char array[24];
char extra[8];

memcpy(array + sizeof array - sizeof extra - 1, extra, sizeof extra);

关于c - 文件数组和赋值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14101259/

相关文章:

javascript - 如何在nodejs中的多个文件之间共享变量

c - 十六进制查找和替换

c - 使用 `ld -r` 并在符号丢失时出现编译错误

c++ - 检测二进制文件的 GCC 编译时标志

java - 我可以将单个 xml 属性解码为多元素数组吗?

excel - KDB:将 2 个或更多表保存到同一个 Excel/CSV 文件(添加页眉和/或页脚)?

c - MIPS 和英特尔 C 编译器之间的宏定义是否兼容?

ruby-on-rails - 检查数组的每个元素是否包含在另一个数组的一组值中

java - 数组中唯一元素的数量

c - 确定打开的文件是否已在 C 中被修改