Reputation: 19
Exercise
Write a program that will compare two text files whose names will be given as a call arguments. This comparison should be carried out line by line, printing out on the screen those lines that differ from the same line in the other file. Print the lines with its line numbers and names of the file they come from. The line numbers should be relative to the beginning of the file, i.e. the first line should have the number 1, the second number 2, etc.
I wrote such a program, but I do not understand how to start read this file from a specific line
int main(void)
{
FILE *a = fopen("D:\\lab9.txt");
FILE *b = fopen("D:\\lab9.1.txt");
int position = 0, line = 1, error = 0;
if(a == NULL || b == NULL)
{
perror("Error occured while opening file.");
exit(0);
}
char x = getc(a);
char y = getc(b);
while(x != EOF && y != EOF)
{
position++;
if(x == '\n' && y == '\n')
{
line++;
pos = 0;
}
if(x != y)
{
error++
}
x = getc(a);
y = getc(b);
}
Upvotes: 1
Views: 481
Reputation: 7482
An approach would be to read the file line by line and start the actual processing when you reach the line that you are looking for:
You can use something like the following to jump to a specific line:
char line[256]; /* or other suitable maximum line size */
while (fgets(line, sizeof line, file) != NULL) /* read a line */
{
if (count >= lineNumber)
{
//process your line in here.
}
else
{
count++;
}
}
I do not think you need to jump to a specific line in order to solve that problem. I would personally solve using something like the following :
IT IS PSEUDO-C - NOT TESTED
int count = 0;
char line1[256]; /* or other suitable maximum line size */
char line2[256]; /* or other suitable maximum line size */
int read1 = fgets(line1, sizeof line1, file1);
int read2 = fgets(line2, sizeof line2, file2);
while (read1 != NULL && read2 != NULL)
{
if( strcmp ( line1, line2))
{
//lines are different. print line number and other info
}
read1 = fgets(line1, sizeof line1, file1);
read2 = fgets(line2, sizeof line2, file2);
}
fclose(file);
}
The previous code is also not handling when files have different number of lines. You should be able to extend yourself.
Upvotes: 1
Reputation: 17493
There are three ways to handle the content of a file:
As you can see, there is no way to start reading a file from a certain line number, or based on the existing content. The only thing you can do is start reading the file from the beginning and browse through the file until you get at the piece of content you're interested in.
Upvotes: 0