我在一项任务中遇到了障碍,我已经被攻击了几天。基本上我需要使用C / C ++创建一个可执行程序,从用户m,n和文件名中获取3个查询。
程序然后将这些行上的文本输出到终端。我必须使用read(),write(),open()和close()系统调用来完成它。
我的方法是通过char去char(我知道的很慢,但我尝试过的其他一切似乎都给出了分段错误)。
但它似乎无法正常工作。当我使用较小的参数时,它只打印整个东西,但如果我使用更大的参数,它根本不会打印任何东西。
谁能告诉我哪里出错了?
// Task 2 of Lab 3
#include<unistd.h> // required library for the system calls
#include<fcntl.h> // required for system calls usage
#include <stdlib.h> // required for the use of exit statement, and atoi
#include<stdio.h> // required for the use of perror
#include<string>
using namespace std;
int main(int argc,char *argv[]){
int m = atoi(argv[1]);
int n = atoi(argv[2]); // taking commmand line args by conversion with atoi
int file; // integer value for holding the file descriptor
ssize_t display;
char *buff[1];
int currentLine = 0;
// open the first file for reading
file = open(argv[3],O_RDONLY);
if(file == -1 ){ // error handler for system call 1: open()
perror("Did not open, exiting...");
exit (1);
}
while(((display = read(file,buff,1)) > 0)){
if(*buff[0] == '\n'){
currentLine++;
}
if((currentLine >= m) && (currentLine <= n)){
if(write(STDOUT_FILENO, buff,display) != display){ // if statement doubles as error handling for read()
perror("Problem with writing..."); // errror handling for write()
exit(-1);
}
}
else{
}
}
file = close(file); // Final system call close()
return 0;
}
示例测试文件:
I have some information in here.
Each line should print to the screen
3 lines total
make that 4
Wait? WHAT! I need 12 minimum???
Hm....
Wellp better start typing then. Let's see what can I write about?
Midterms are coming
They scare me
I hate exams, but I love code
woah i also need numbers in here uh 23
19 and lets do 100 and 400 just to add a couple more
maybe i should go ahead and add a 903 here
300
and that previous 300 got it's own line
with this file ...
I have a good mix of chars,numbers, and symbols
that's good enough
time to test!