0

I am fairly new to C and I am making a C program that should works like this: it has one thread which reads a file with a double on each line of the file, and:

  1. it should be able to read files of any size.
  2. after reading the double it should perform this n=atan(tan(n) calculation.

I have the following example:

void* ReadFile(void *file){
    char *str;
    str = (char*)file;
    printf("Opening File\n");
    FILE* f = fopen(str,"w");
    fclose(f);
    printf("Closing File\n");
}

void main(){
    pthread_t t1;
    pthread_create(&t1,NULL,open_file,"data.txt");
    pthread_join(t1,NULL);
}

where should I perform the operation? should it be in main or in ReadFile is also fine. The other problem I have is that how can you make sure it reads a file of any size? Should I use sizeof(str) in order to get the length/size of the file and then make a for loop that reads a line at each iteration and performs the calculation? Is this a good way of doing this in C?

Paul Floyd
  • 5,530
  • 5
  • 29
  • 43
S. N
  • 3,456
  • 12
  • 42
  • 65
  • Don't you mean `pthread_create(&t1, NULL, ReadFile, "data.txt")`? Check up on `fscanf` (http://en.cppreference.com/w/cpp/io/c/fscanf) for reading the double from the file. – Paul Floyd Mar 29 '18 at 13:56
  • Why are you using a thread if all the code does is process that file? – Chris Turner Mar 29 '18 at 13:57

1 Answers1

0

Yours is a two-part question:

  1. Given an input FILE* f of indeterminate size consisting of lines with doubles on them, how do I read it and perform something for each double?

The answer: like this:

double d;
while(EOF!=fscanf(f, " %lf", &d))
    //do_something_with_d: printf("read=%lf\n", d);

It's a streaming operation. fscanf will read the file a buffer at a time (the buffer is hidden in FILE) so you don't need the file size anywhere (the file could well be a socket or a pipe-connected process that generates and infinite sequence of doubles -- the streaming approach will handle all these cases), not to mention that sizeof str will give you the size of a char* pointer (typically 8 or 4).

The second part of your question -- how to do it in a thread -- you've pretty much already solved and there's only one place you can plug the fscanf loop -- where you've opened the file, i.e., in between the calls to fopen and fclose.

Petr Skocik
  • 58,047
  • 6
  • 95
  • 142