[英]Any advice for reading in char arrays from text files in C?
Here's my issue I'm running into. 这是我遇到的问题。
I'm reading in lines of text from a file, but only trying to read in lines that aren't consecutive repeats. 我正在读取文件中的文本行,但仅尝试读取非连续重复的行。
Here's my regular code for reading in the lines of text. 这是我用于阅读文本行的常规代码。
while (((ch = getc (fp)) != EOF))
{
a[j++] = ch;
}
a[j] = '\0';
which works just fine. 效果很好。
When trying to figure out how to go about the problem, I tried having a char array that would read in a line at a time, and then compare it to the previous line using strcomp. 当试图解决该问题时,我尝试使用一个char数组,一次读取一行,然后使用strcomp将其与上一行进行比较。 If it was a match, it would not add that line into the final char array.
如果匹配,则不会将该行添加到最终的char数组中。 It looks something like this:
看起来像这样:
while (((ch = getc (fp)) != EOF))
{
if (ch != '\n')
{
copynumber++;
temp[j] = ch;
}
else
{
uni = strcmp(identical, final);
if (uni == 0) {
copynumber = 0;
}
else
{
strncpy(identical, temp, copynumber);
final[j] = ch;
}
j++;
}
}
final[j] = '\0';
but I know this won't work for a few reasons. 但我知道由于某些原因,这将无法正常工作。 One, I never add the previous chars into the final array.
第一,我从不将以前的字符添加到最终数组中。 I'm really just lost.
我真的迷路了。 Any help is appreciated.
任何帮助表示赞赏。 Thank you.
谢谢。
There is a getline()
function in stdio.h
that you can use to get each line in a file. stdio.h
中有一个getline()
函数,可用于获取文件中的每一行。
To skip duplicates you can store the previous line read and compare at each step. 要跳过重复项,您可以存储上一步读取的行,并在每个步骤进行比较。
FILE *fp;
char *line = NULL;
char *prev_line[999];
char final[999];
size_t len = 0;
ssize_t read;
fp = fopen("file", "r");
while ((read = getline(&line, &len, fp)) != -1) { // Read each line
if (strncmp(line, prev_line, read) != 0) { // If not equal
strncat(final, line, read); // Copy to final
strncpy(prev_line, line, read); // Update previous
}
}
free(line); // Need to free line since it was null when passed to getline()
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.