1. This site uses cookies. By continuing to use this site, you are agreeing to our use of cookies. Learn More.

Questin about files

Discussion in 'C' started by tzina, May 21, 2013.

  1. tzina

    tzina New Member

    Joined:
    May 21, 2013
    Messages:
    1
    Likes Received:
    0
    Trophy Points:
    0
    Hi!!!I have a question...How can I use the data of a file???
    For example at the following code:
    Code:
    #include <stdio.h>
    int main()
    {
    FILE *fp;
    int i,n;
    fp = fopen("d.dat","w");
    if (fp==NULL) {
        exit(0);
    }
    for (i=0; i<=10; i++){
    	 printf("Give number:");
    	 scanf("%d",&n);
    	 fprintf(fp,"%d,%d\n",n,i*n);
    }	   
    fclose(fp);
    return 0;
    }
    I want to write a function that finds the max of the numbers i*n,that exist in the file "d.dat"...How can I do this????
     
  2. hobbyist

    hobbyist New Member

    Joined:
    Jan 7, 2012
    Messages:
    141
    Likes Received:
    0
    Trophy Points:
    0
    open the file using "w+" so you can write and read from it. After your write operation finishes, rewind the stream so that you can read its data.

    Code:
    for(...)
    {
       fprintf(...)
    }
    
    rewind(fp);
    fseek(fp, 0, SEEK_SET); // same as rewind but w/o resetting eof bits
    
    while(fscanf(fp, "%d", &n) == 1)
       // do something with n
    
    As for a function, you could probably pass in a second parameter by reference indicating the max number in the file.

    Code:
    void findMax(int curval, int *curmax)
    {
        if(curval > *curmax)
            *curmax = curval;
    }
    In the read back of the file
    Code:
    int n, some_max = 0;
    ...
    // loop for adding to file
    ...
    while(fscanf(...) == 1)
        findMax(n, &some_max);
    
    Maybe something like that

    You are aware that the contents of the file get over written each time the program is run using "w" or "w+"?? If that's a problem, then create the file first and open it using "r+' or "a+".
     
  3. NewsBot

    NewsBot New Member

    Joined:
    Dec 2, 2008
    Messages:
    1,267
    Likes Received:
    2
    Trophy Points:
    0
    Moved to C Programming from Introduction.
     

Share This Page