1

我想在文件中找到'\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
4

1 回答 1

3

我想在文件中找到'\n'的位置并打印出\n之后的剩余字符

#include <stdio.h>

long long find_first_newline_then_print(FILE *fn) {
  int ch;
  long long pos = 0;
  while ((ch = fgetc(fin)) != EOF && ch != '\n') ++pos;
  if (ch == EOF) return -1;
  while ((ch = fgetc(fin)) != EOF) fputc(ch, stdout);
  return pos + 1;
}
于 2019-08-17T05:29:48.820 回答