I want to find the position of a '\n' in a file and print out the remaining characters after \n
I've tried to use lseek to find the number of times '\n' occurred but I cannot seem to find the position at which the special character '\n' occurs
I've also tried using strok to break the particular file down and lseek to find the position of the last character
#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
three lines printed
some text
a break occured
some text
a break occured
some text
a break occured
instead it prints the number of characters in the file and formats it based on when a \n occurred
.. ext
a break occured
I want to find the position of a '\n' in a file and print out the remaining characters after \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;
}