我想在文件中找到'\n'的位置并打印出\n之后的剩余字符
我尝试使用 lseek 查找 '\n' 出现的次数,但我似乎无法找到特殊字符 '\n' 出现的位置
我也尝试使用strok来分解特定文件并lseek找到最后一个字符的位置
#define MAX_BUFFER_LENGTH 512
//path name is the file that is being accessed
void printLines(char *initPathName, char *initBuffer, int initnumberRead)
{
int fileDescriptor;
int numOfBreaks =0;
char *pathName=initPathName;
fileDescriptor = open(pathName, O_RDONLY);
lseek(fileDescriptor,initnumberRead * -1, SEEK_END);
int size = read(fileDescriptor, initBuffer, MAX_BUFFER_LENGTH);
initBuffer[size] = '\0';
char *token = strtok(initBuffer, "\\\n\r");
for(int i= 0;token !=NULL;i++)
{
write(2,token, strlen(token));
write(2,"\n", 2);
write(2,"a break occured\n", 17);
token = strtok(NULL,"\\\n\r");
}
close(fileDescriptor);
}
输入
./program some.txt -l 3 // this prints the number of lines to be printed and separated with line breaks
应该做什么
打印三行
some text
a break occured
some text
a break occured
some text
a break occured
输出
相反,它会打印文件中的字符数并根据 \n 发生的时间对其进行格式化
.. ext
a break occured