我编写了一个函数,它使用 read() 系统调用从文件中读取数字并将它们放入数组中。但是,我注意到最后总是包含一个额外的 0。
int numberRead = 0;
int fp;
char buf[512];
size_t nbytes = sizeof(buf);
int n;
int counter = 0;
char* ptr;
size_t curSize = 16;
int radix = hexFlag ? 16 : 10;
*array = malloc(curSize * sizeof(*array));
fp = open(fname, O_RDONLY);
if (fp == -1) {
return -1;
}
while ((n = read(fp, buf, nbytes)) != 0) {
ptr = strtok(buf, " \n");
while(ptr) {
if (counter >= curSize) {
curSize += 16;
*array = realloc(*array, …Run Code Online (Sandbox Code Playgroud)