Files,question about data
CodeGuru Home VC++ / MFC / C++ .NET / C# Visual Basic VB Forums Developer.com
Results 1 to 3 of 3

Thread: Files,question about data

  1. #1
    Join Date
    Apr 2013
    Posts
    45

    Files,question about data

    Hi!!!!I have a question...How can I use the data from a file????For example at the following code 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????Thank you!!!
    #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;
    }

  2. #2
    Join Date
    Dec 2012
    Location
    England
    Posts
    2,263

    Re: Files,question about data

    If you want to read data from a file using the FILE set of functions, then you need to open the file for reading.

    Code:
    fp = fopen("d.dat", "r");
    Then assuming the file contains numbers in the format n,n then you can read the numbers using
    Code:
    fscanf(fp, "%d,%d", &n, &in);
    You loop on fscanf until it returns EOF to indicate that all the numbers have been read.

    This gives the program to input the numbers, create the file, read and display from the file and print the largest i*n number as

    Code:
    #include <stdio.h>
    
    int main()
    {
    FILE	*fp;
    
    int	i,
    	n,
    	in,
    	max = -999999999;
    
    	if ((fp = fopen("d.dat", "w")) == NULL)
    		return 1;
    
    	for (i = 0; i <= 10; i++){
    		printf("Give number:");
    		scanf("%d", &n);
    		fprintf(fp, "%d,%d\n" ,n, i * n);
    	}
    	fclose(fp);
    
    	if ((fp = fopen("d.dat", "r")) == NULL)
    		return 2;
    
    	while (fscanf(fp, "%d,%d", &n, &in) != EOF) {
    		printf("n is %d, in is %d\n", n, in);
    		if (in > max)
    			max = in;
    	}
    
    	printf("The largest i*n is %d\n", max);
    	fclose(fp);
    
    	return 0;
    }
    Last edited by 2kaud; May 22nd, 2013 at 04:00 AM.
    All advice is offered in good faith only. You are ultimately responsible for effects of your programs and the integrity of the machines they run on.

  3. #3
    Join Date
    Apr 2013
    Posts
    45

    Red face Re: Files,question about data

    Thank you very much...!!!!!!

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  


Azure Activities Information Page

Windows Mobile Development Center


Click Here to Expand Forum to Full Width

This is a CodeGuru survey question.


Featured


HTML5 Development Center