C Programming: Reading integers from text file until the end of a line: I need h
ID: 642186 • Letter: C
Question
C Programming: Reading integers from text file until the end of a line:
I need help understanding on how to read integers from a text file until the end of its line, and then holding them in a hashtable where each line can be checked if theirs a duplicate.
Example:
0x7f1a9804ae19
0x7f1a9804ae1c
0x7f1a9804ae1c
0x7f1a9804ae1c
Output:
2
I have used fgetc which gets only reads until the end of the string, but I cannot read the integers. I need to read the integers so that I am able to store in Hashtable.
Heres a sample of my code that I worked on:
int main(int argc, char** argv)
{
FILE *fp;
char ch[60];
int table[100];
int counter = 0;
int num;
int j = 0;
int i = 0;
long size;
int n;
if (argc != 2)
{
printf("error ");
return 0;
}
if ((fp = fopen(argv[1], "rt")) == NULL){
printf("0 ");
return 0;
}
fp = fopen(argv[1],"rt");
while((num = fgetc(fp)) != EOF){
if(fgets(ch, 60, fp) != NULL){
puts(ch);
n = atoi(ch);
printf("%d ",n);
}
fclose(fp);
return 0;
}
Explanation / Answer
Use fgets() to read a full line, then parse the line (possibly with strtol()).
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.