先决条件: C中文件处理的基础
给定目录中的文本文件,任务是先打印文件的所有奇数行内容,然后打印所有偶数行内容。
例子:
Input: file1.txt:
Welcome
to
GeeksforGeeks
Output:
Odd line contents:
Welcome
GeeksforGeeks
Even line contents:
to
Input: file1.txt:
1. This is Line1.
2. This is Line2.
3. This is Line3.
4. This is Line4.
Output:
Odd line contents:
1. This is Line1.
3. This is Line3.
Even line contents:
2. This is Line2.
4. This is Line4.
方法:
- 在a +模式下打开文件。
- 在文件末尾插入新行,以使输出不会生效。
- 通过保持选中状态打印文件的奇数行,而不会打印文件的偶数行。
- 倒带文件指针。
- 重新初始化检查。
- 通过保持一个检查,不打印文件的奇数行打印文件的偶数行。
下面是上述方法的实现:
// C program for the above approach
#include
// Function which prints the file content
// in Odd Even manner
void printOddEvenLines(char x[])
{
// Opening the path entered by user
FILE* fp = fopen(x, "a+");
// If file is null, then return
if (!fp) {
printf("Unable to open/detect file");
return;
}
// Insert a new line at the end so
// that output doesn't get effected
fprintf(fp, "\n");
// fseek() function to move the
// file pointer to 0th position
fseek(fp, 0, 0);
int check = 0;
char buf[100];
// Print Odd lines to stdout
while (fgets(buf, sizeof(buf), fp)) {
// If check is Odd, then it is
// odd line
if (!(check % 2)) {
printf("%s", buf);
}
check++;
}
check = 1;
// fseek() function to rewind the
// file pointer to 0th position
fseek(fp, 0, 0);
// Print Even lines to stdout
while (fgets(buf, sizeof(buf), fp)) {
if (!(check % 2)) {
printf("%s", buf);
}
check++;
}
// Close the file
fclose(fp);
return;
}
// Driver Code
int main()
{
// Input filename
char x[] = "file1.txt";
// Function Call
printOddEvenLines(x);
return 0;
}
输入文件:
输出文件:
想要从精选的最佳视频中学习和练习问题,请查看《基础知识到高级C的C基础课程》。