有没有办法在 C 文件中找到特殊字符 '\n' 的位置?
Is there a way to find the position of a special character '\n' in a file in C?
我想在一个文件中找到'\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] = '[=10=]';
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
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;
}
我想在一个文件中找到'\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] = '[=10=]';
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
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;
}