【发布时间】:2015-03-22 04:51:28
【问题描述】:
这是我正在为课堂练习的练习,我不明白为什么它不会运行......
我在尝试分配长度来自变量 (num2) 的 char 数组(缓冲区)时遇到问题。
你可以像这样执行文件:
./file.c offset numOfChars filename.txt
./file.c 4 10 somefile.txt
如果某个文件包含文本:
为什么这个 c 程序不工作。我想不通
程序应该打印
这不是
代码如下:
#include <stdio.h>
#include <unistd.h>
#include <fcntl.h>
#include <sys/types.h>
#include <sys/stat.h>
main(int ac, char *av[]){
// Save the command line variables
int num1 = av[1];
int num2 = av[2];
long numbyte1 = av[1];
long numbyte2 = av[2];
int fd = open(av[3], O_RDONLY);
// Try to open the file
if( fd < 0 )
perror(fd + " - Could not open file!");
// use stat to get file size
struct stat sb;
if(fstat(fd,&sb) < 0)
return 1;
// Check to see if the file is big enough for the provided offset
if(sb.st_size < num1+num2){
perror(fd + " - Size of file is not large enough for provided offset!" + fd);
}
char buffer[num2];
if(lseek(fd, numbyte1 ,SEEK_SET) < 0) return 1;
if(read(fd, buffer, numbyte2) != numbyte2) return 1;
printf("%s\n", buffer);
return 0;
}
【问题讨论】:
-
(1) 注意你的编译器警告。 (2) 确保您的编译器向您发出警告(您可能正在使用
gcc,所以-Wall是最低限度;我使用-Wall -Wextra -Werror -Wstrict-prototypes -Wmissing-prototypes -std=c11)。 (3) 如果遇到问题,请打印数据——对于lseek(),也打印您要查找的偏移量。我知道您认为您知道该值,但您不知道该值,并且打印该值会告诉您您的偏移量完全错误。如有疑问,请让程序告诉您它在做什么。这是一项关键但基本的调试技术。