我想在文件中找到'\ 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
答案 0 :(得分: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;
}