C语言 为什么没有任何写作



我正在做C的家庭作业,我有一个小问题。这里我想读取一个文件并在终端中显示它问题是需要控制缓冲区的大小,并且不等于文件的大小即使没有这个,我也试着让它在大小上工作,但它没有,我想是因为一个无限循环,因为当我运行命令时,什么都没有发生,我也不能写其他命令下面是我的代码:

void cat(int size, const char * path){
char *buf = malloc(size);
int fd = open(path , O_RDONLY) ;
off_t taille = lseek(fd,0,SEEK_END) ;
int n = 0 ;
lseek(fd,0,SEEK_SET) ;
while(n<taille){
n+= read(fd,buf + n , taille -n-1 ) ;
}
write(STDOUT_FILENO , buf , taille) ;
} 

提前谢谢你。

访问不允许触摸的内存会导致未定义行为。

void cat(int size, const char * path){
char *buf = malloc(size);
int fd = open(path , O_RDONLY) ;
off_t taille = lseek(fd,0,SEEK_END) ;
int n = 0 ;
lseek(fd,0,SEEK_SET) ;
while(n<taille){
n+= read(fd,buf + n , taille -n-1 ) ;  // << buf can hold only up to size bytes.
}
write(STDOUT_FILENO , buf , taille) ;
} 

对于任何file_size > size,这会导致非法访问内存,这可能会导致段错误或在开始写任何输出之前任何其他中止。

由于您的赋值明确地告诉您不要将整个文件放在缓冲区中,您需要以块的方式处理文件I/O:

void cat(int size, const char * path) {
char *buf = malloc(size);      // TODO: Add check for NULL
int fd = open(path, O_RDONLY); // TODO: Add check for < 0
off_t taille = lseek(fd,0,SEEK_END);
int n = 0;
lseek(fd,0,SEEK_SET);
while (n<taille) {
ssize_t readbytes = read(fd, buf, size);
write(STDOUT_FILENO, buf, readbytes);
n += readbytes;
}
fclose(fd);
} 

或简单的:

void cat(int size, const char * path) {
char *buf = malloc(size);      // TODO: Add check for NULL
ssize_t fd = open(path, O_RDONLY); // TODO: Add check for < 0
ssize_t readbytes;
while ((readbytes = read(fd,buf , size)) > 0) {
write(STDOUT_FILENO, buf, readbytes);
}
// TODO: check for readbytes < 0
fclose(fd);
} 

未测试代码

相关内容

最新更新