gpt4 book ai didi

c - 在linux系统上顺序打开和读取多个文件

转载 作者:太空宇宙 更新时间:2023-11-04 08:16:08 24 4
gpt4 key购买 nike

我有一个名为 file.txt 的文件,其中包含其他文件路径作为内容。现在,我试图打开我的“file.txt”,读取每个 line 并将每个内容加载到捕获的行中,因为我的行是一个文件路径。请参阅下面我的 file.txt 包含的内容:

file.txt:包含

/Desktop/path1.txt
/Desktop/path2.txt

和,

/Desktop/path1.txt:包含

something...is here in this line
do you have you iurgiuwegrirg
ewirgewyrwyier
jhwegruyergue

/Desktop/path2.txt:包含类似..的内容

abcd
efg
jshdjsdd

最后,如上所述,我想:

1.open file.txt
2.read each line, here line is a path
3.open line as a path,(/Desktop/path1.txt ...and /Desktop/path2.txt)
4.read contents in each path.

看看我的作品:

ma​​in.c

#define _GNU_SOURCE
#include <stdio.h>
#include <stdlib.h>
#define PATH "file.txt"

void load_data_path(char *data_path)
{
FILE *stream;
char *line = NULL;
size_t len = 0;
ssize_t read;

stream = fopen(data_path, "r");
if (stream == NULL)
{
printf("FILE..not found\n");
exit(EXIT_FAILURE);
}
while ((read = getline(&line, &len, stream)) != -1)
{
printf("Content in path: %s", line);
}
free(line);
fclose(stream);
exit(EXIT_SUCCESS);
}
void load_parent_path(char *init_path)
{
FILE *stream;
char *line = NULL;
size_t len = 0;
ssize_t read;

stream = fopen(init_path, "r");
if (stream == NULL)
{
exit(EXIT_FAILURE);
}
while ((read = getline(&line, &len, stream)) != -1)
{
printf("Current path from parent file: %s\n", line);
//pass a current line, a path to another reader function
load_data_path(line);
}
free(line);
fclose(stream);
exit(EXIT_SUCCESS);
}

int main(void)
{
//PATH="file.txt", this functions reads contents of file.txt
load_parent_path(PATH);
}

问题是,当我运行 main.cpp 时,它显示 FILE...not found,来自 void load_data_path(char *data_path) 函数。和 segfault 当我删除 exit(EXIT_SUCCESS);

有什么建议吗?谢谢。

最佳答案

getline() reads an entire line from stream, storing the address of the buffer containing the text into *lineptr. The buffer is null- terminated and includes the newline character, if one was found.

您可以使用以下方法删除结尾的换行符:

char *p = strchr(line, '\n');
if (p != NULL) *p = '\0';

关于c - 在linux系统上顺序打开和读取多个文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35717545/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com