Reputation: 23
In this function findBookByTitle what is supposed to happen is fp is opened and if a title matches the one given to function it will print the title. It is assumed titles are unique so once a match is found it can stop searching. My problem is i'm not entirely sure how to match the title to something in a file. This is what I have so far...
void findBookByTitle(FILE* fp, char title[])
{
FILE * fp = fopen(fp, "r");
while(!EOF && *fp = title){
printf("Title: <%c> \n", title);
}
if(EOF && *fp != title ){
printf("No books match the title: <%c> ", title);
}
}
As well when I compile I get a few errors, it might be pointless to address these as my function remains incomplete but a few of these really confuse me.
34: error: 'fp' redeclared as different kind of symbol 32: note: previous definition of 'fp' was here 34: warning: passing argument 1 of 'fopen' from incompatible pointer type /usr/include/stdio.h:251: note: expected 'const char * restrict' but argument is of type 'struct FILE *' 35: error: invalid operands to binary && (have 'int' and 'FILE') 38: error: invalid operands to binary != (have 'FILE' and 'char *')
Upvotes: 2
Views: 1981
Reputation: 14792
FILE *pt
twiceFILE
pointer with a string (char *
)%c
EOF
is -1
and with the operator !
this is true if EOF
is 0
but EOF
will never changeThe right code should be right (so far I've understand your problem):
#include <stdio.h>
#include <string.h>
void findBookTitle(char *path, char **title, int titles) {
FILE *fp = fopen(path, "r");
char line[100];
int i = 0, count = 0;
while (fgets(line, 100, fp) != NULL) {
while (i < titles)
if (!strcmp(title[i], line)) {
printf("Title: <%s>\n", line);
count++;
}
i = 0;
}
if (!count)
printf("No books found.\n");
}
Upvotes: 0
Reputation:
Your function is declared as taking a FILE *
as its first argument, but it then proceeds to treat that argument as if it's a filename and try to open another FILE *
(with the same name!) using it. Make up your mind on whether the argument is a FILE *
or a char *
, and change your code accordingly.
You are trying to use EOF
to test for EOF on fp
. It's not quite that simple. Try feof(fp)
instead.
You are trying to read from fp
using *fp = title
(and *fp != title
). This doesn't make any sense at all. You need to use a function to read from the file pointer, such as fgets
or fscanf
.
Upvotes: 4
Reputation: 141829
You are overwriting the value in your file pointer with a pointer to a char when you use assignment like that (*fp = title
). After that all kinds of problems will happen.
You probably also need to remove the line:
FILE * fp = fopen(fp, "r");
Since you already have a FILE *
fp isn't the name of a file to open. It's an already opened file.
Upvotes: 0