对于类中的作业,我们的任务是使用read()函数读取包含数字的文件。虽然我可以将数字读取到缓冲区中,但我无法将它们从缓冲区移到char *数组中,以便可以轻松地访问和排序。任何建议都是值得感谢的。
int readNumbers(int hexI, int MAX_FILENAME_LEN, int **array, char* fname) {
int numberRead = 0, cap = 2;
*array = (int *)malloc(cap*sizeof(int));
int n;
int filedesc = open(fname, O_RDONLY, 0);
if(filedesc < 0){
printf("%s: %s\n", "COULD NOT OPEN", fname);
return -1;
}
char * buff = malloc(512);
buff[511] = '\0';
while(n = read(filedesc, buff+totaln, 512 - totaln) > 0) //Appears to loop only once
totaln += n;
int len = strlen(buff);
for (int a = 0; a < len; a++) { //Dynamically allocates array according to input size
if ((&buff[a] != " ") && (&buff[a] != '\n'))
numberRead++;
if (numberRead >= cap){
cap = cap*2;
*array = (int*)realloc(*array, cap*sizeof(int));
}
}
int k = 0;
while((int *)&buff[k]){ //attempts to assign contents of buff to array
array[k] = (int *)&buff[k];
k++;
}
}发布于 2014-11-04 05:55:31
您使用read()是错误的。至少有两个严重的错误:
你可以忽略返回值,除非end-of-file.
如果您希望在read()返回后将更多数据读入同一缓冲区,而不覆盖已读取的内容,则必须将指针传递到缓冲区中的第一个可用位置。如果您想知道总共读取了多少字节,则需要添加返回值。通常的范例是这样的:
/*
* Read as many bytes as possible, up to buf_size bytes, from file descriptor fd
* into buffer buf. Return the number of bytes read, or an error code on
* failure.
*/
int read_full(int fd, char buf[], int buf_size) {
int total_read = 0;
int n_read;
while ((n_read = read(fd, buf + total_read, buf_size - total_read)) > 0) {
total_read += n_read;
}
return ((n_read < 0) ? n_read : total_read);
}在按照这些思路做了一些事情并且没有收到错误之后,您可以确信除了buf[total_read - 1]之外,read()没有修改缓冲区的任何元素。它肯定没有用零填充缓冲区的其余部分。
请注意,在缓冲区已满之前并不总是需要或希望进行读取;示例函数执行此操作是出于演示目的,因为它似乎就是您想要的。
完成此操作后,请注意您正在尝试提取数字,就好像它们是以二进制形式记录在文件中的一样。可能确实是这样,但是如果您正在读取包含格式化数字的文本文件,那么您需要以不同的方式提取数字。如果这就是您想要的,那么在读取的最后一个字节之后添加一个字符串终止符,并使用sscanf()来提取数字。
https://stackoverflow.com/questions/26723437
复制相似问题