Thread: Reading File Issue

  1. #1
    Registered User
    Join Date
    Mar 2007
    Posts
    19

    Reading File Issue

    I'm pretty lost when it comes to reading/writing, I've paid attention in my class, read multiple online tutorials, and the book and I can't figure it out. I tried to do this assignment, but it just crashes when I execute it.

    Code:
    #include <stdio.h>
    #include <stdlib.h>
    #include <conio.h>
    #define MAXNUM 6
    
    
    int main()
    {
    	FILE *fp;
    	char *mode = "r";
    	int i=0;
    	char fName[MAXNUM] = {0}, lName[MAXNUM] = {0};
    	int carNum[MAXNUM] = {0}, milesDriven[MAXNUM] = {0}, usedGallons[MAXNUM] = {0};
    	double milesPerGallon[MAXNUM] = {0};
    	int totalMiles = 0, totalGallons = 0;
    	double totalMPG = 0, averageMPG = 0;
    
    	fp = fopen("cars.dat", "r");
    
    	if (fp == NULL) 
    	{
    		printf("Can't open input file cars.dat!\n");
    		exit(1);
    	}
    
    	for (i=0; i<MAXNUM; i++)
    	{
    		fscanf(fp, "&#37;c %c %d %d %d", fName[i], lName[i], carNum[i], milesDriven[i], usedGallons[i]);  //Assigns variables from file
    		totalMiles += milesDriven[i];  //Sums total miles
    		totalGallons += usedGallons[i];  //Sums total gallons
    		milesPerGallon[i] = (milesDriven[i] / usedGallons[i]);  //Calculates MPG
    	}
    
    	for (i=0; i<MAXNUM; i++)
    		totalMPG += milesPerGallon[i];  //Sums total MPG
    	averageMPG = (totalMPG / MAXNUM);  //Calculates Avg MPG
    
    	
    	printf("Last_Name First_Name Car_No. Miles_Driven Gallons_Used MPG");  //print header
    	for (i=0; i<MAXNUM; i++)  //prints charts
    		printf("%c %c %d %d %d %d\n", fName[i], lName[i], carNum[i], milesDriven[i], usedGallons[i], milesPerGallon[i]);
    
    
    	fclose(fp);
    	getch();
    
    	return 0;
    }
    Last edited by dr0be; 05-05-2007 at 02:26 PM.

  2. #2
    and the hat of int overfl Salem's Avatar
    Join Date
    Aug 2001
    Location
    The edge of the known universe
    Posts
    39,661
    After removing all the // comments, which are not legal C
    Code:
    $ gcc -W -Wall -ansi -pedantic -O2 foo.c
    foo.c: In function `main':
    foo.c:28: warning: format argument is not a pointer (arg 3)
    foo.c:28: warning: format argument is not a pointer (arg 4)
    foo.c:28: warning: format argument is not a pointer (arg 5)
    foo.c:28: warning: format argument is not a pointer (arg 6)
    foo.c:28: warning: format argument is not a pointer (arg 7)
    foo.c:41: warning: int format, double arg (arg 7)
    foo.c:10: warning: unused variable `mode'
    Pay very close attention to the way you're calling printf and scanf functions.
    If you dance barefoot on the broken glass of undefined behaviour, you've got to expect the occasional cut.
    If at first you don't succeed, try writing your phone number on the exam paper.

  3. #3
    Registered User
    Join Date
    Mar 2007
    Posts
    19
    I have no clue what any of that foo.c: things are, what did I do wrong when calling fscanf function?

  4. #4
    Frequently Quite Prolix dwks's Avatar
    Join Date
    Apr 2005
    Location
    Canada
    Posts
    8,057
    Well, first, the warnings like these:
    Code:
    foo.c:28: warning: format argument is not a pointer (arg 3)
    They mean that you're not passing fscanf() a pointer. That is, you have code like this
    Code:
    int i;
    scanf("&#37;d", i);
    instead of like this
    Code:
    int i;
    scanf("%d", &i);
    This warning
    Code:
    foo.c:41: warning: int format, double arg (arg 7)
    means that you have %d but need %f.

    And this one
    Code:
    foo.c:10: warning: unused variable `mode'
    means that you declare a variable called mode but you never use it. So you can get rid of the variable.
    dwk

    Seek and ye shall find. quaere et invenies.

    "Simplicity does not precede complexity, but follows it." -- Alan Perlis
    "Testing can only prove the presence of bugs, not their absence." -- Edsger Dijkstra
    "The only real mistake is the one from which we learn nothing." -- John Powell


    Other boards: DaniWeb, TPS
    Unofficial Wiki FAQ: cpwiki.sf.net

    My website: http://dwks.theprogrammingsite.com/
    Projects: codeform, xuni, atlantis, nort, etc.

  5. #5
    Malum in se abachler's Avatar
    Join Date
    Apr 2007
    Posts
    3,195
    I think he means you are passing by value instead of by pointer

    p.s. you should change:
    Code:
    fp = fopen("cars.dat", "r");
    to:
    Code:
    fp = fopen("cars.dat", "r+b");
    you shoudl also post the contents of cars.dat so we can check your input source

  6. #6
    Frequently Quite Prolix dwks's Avatar
    Join Date
    Apr 2005
    Location
    Canada
    Posts
    8,057
    Quote Originally Posted by abachler View Post
    p.s. you should change:
    Code:
    fp = fopen("cars.dat", "r");
    to:
    Code:
    fp = fopen("cars.dat", "r+b");
    Why? The OP reads from the file with fscanf(), so it should be opened in text mode ('t'), not binary mode ('b'); and the program never attempts to write to the file, so there's no need to use "r+".
    dwk

    Seek and ye shall find. quaere et invenies.

    "Simplicity does not precede complexity, but follows it." -- Alan Perlis
    "Testing can only prove the presence of bugs, not their absence." -- Edsger Dijkstra
    "The only real mistake is the one from which we learn nothing." -- John Powell


    Other boards: DaniWeb, TPS
    Unofficial Wiki FAQ: cpwiki.sf.net

    My website: http://dwks.theprogrammingsite.com/
    Projects: codeform, xuni, atlantis, nort, etc.

  7. #7
    Registered User
    Join Date
    Mar 2007
    Posts
    19
    Alright, well I changed all my fscanf's with &'s, since I forgot them, but the program is still crashing.


    *EDIT* All the program needs to do is read a .dat file, assign variables to the data, then display output stuff in a normal printf box, Im just confused on how exactly to assign file data to a variable, which is I believe why the program is crashing.

    Code:
    for (i=0; i<MAXNUM; i++)
    	{
    		fscanf(fp, "&#37;c", &fName[i]);          /**/
    		fscanf(fp, "%c", &lName[i]);          /**/
    		fscanf(fp, "%d", &carNum[i]);          /*Assigns variables from file*/
    		fscanf(fp, "%d", &milesDriven[i]);    /**/
    		fscanf(fp, "%d", &usedGallons[i]);    /**/
                    totalMiles += milesDriven[i];  /*Sums total miles*/
    		totalGallons += usedGallons[i];  /*Sums total gallons*/
    		milesPerGallon[i] = (milesDriven[i] / usedGallons[i]);  /*Calculates MPG*/
    	}

  8. #8
    Frequently Quite Prolix dwks's Avatar
    Join Date
    Apr 2005
    Location
    Canada
    Posts
    8,057
    Code:
    milesPerGallon[i] = (milesDriven[i] / usedGallons[i]);  /*Calculates MPG*/
    Since both milesDriven[] and usedGallons[] are ints, you're performing integer division. The answer will be truncuated. I assume this is not what you want, because you're storing the result in a floating point variable, a double. Cast one of the numbers to a double:
    Code:
    milesPerGallon[i] = ((double)milesDriven[i] / usedGallons[i]);  /*Calculates MPG*/
    How is it crashing?

    You should enable warnings -- you get much better and more thorough diagnostics. For Dev-C++, in the Compiler Options dialog box, add "-W -Wall" (without quotes) to the "pass extra parameters to the compiler" option.
    dwk

    Seek and ye shall find. quaere et invenies.

    "Simplicity does not precede complexity, but follows it." -- Alan Perlis
    "Testing can only prove the presence of bugs, not their absence." -- Edsger Dijkstra
    "The only real mistake is the one from which we learn nothing." -- John Powell


    Other boards: DaniWeb, TPS
    Unofficial Wiki FAQ: cpwiki.sf.net

    My website: http://dwks.theprogrammingsite.com/
    Projects: codeform, xuni, atlantis, nort, etc.

  9. #9
    Registered User
    Join Date
    Mar 2007
    Posts
    19
    I am using Microsoft Visual C++ 6.0, so I'm not really sure where to turn on warning, id search for it, but something happened with the MSDN when I installed it and I do not have the CD (back at school).

    I casted the one variable like you suggested and it didnt crash this time but I got a bunch of weird info, names were truncated and such it looks like

    Code:
    Last_Name   First_Name   Car_No.   Miles_Driven   Gallons_Used   MPG
    J o 0 0 0 -1.#IND00
    h n 0 0 0 -1.#IND00
    J o 0 0 0 -1.#IND00
    n e 0 0 0 -1.#IND00
    s   55 250 20 12.500000
    
     M 0 0 0 -1.#IND00
    The side spells "John Jones" which is suppose to be displayed on the same line, and "55", "250", "20", and "12.5" are right, but in the completely wrong place, suppose to all be on first line and look like "John Jones 55 250 20 12.5"

  10. #10
    Frequently Quite Prolix dwks's Avatar
    Join Date
    Apr 2005
    Location
    Canada
    Posts
    8,057
    You want &#37;c to read in "John"? Well, it's not going to. Try using a char[] array with %s.
    dwk

    Seek and ye shall find. quaere et invenies.

    "Simplicity does not precede complexity, but follows it." -- Alan Perlis
    "Testing can only prove the presence of bugs, not their absence." -- Edsger Dijkstra
    "The only real mistake is the one from which we learn nothing." -- John Powell


    Other boards: DaniWeb, TPS
    Unofficial Wiki FAQ: cpwiki.sf.net

    My website: http://dwks.theprogrammingsite.com/
    Projects: codeform, xuni, atlantis, nort, etc.

  11. #11
    Registered User
    Join Date
    Mar 2007
    Posts
    19
    Well I was trying to have this...
    Code:
    fscanf(fp, "&#37;c", &fName[i]);
    Assign fName[0] to be 'John'

    Then this...
    Code:
    printf("%c", fName[0]);
    Would print it, but it doesnt seem to be working.

    *EDIT* I printed just the single fName[0] outside of a for statement and it just printed 1 char, so when its being assigned from the file its only assigning 1 char per array value.
    fName[0] = J
    fName[1] = o
    fName[2] = h
    fName[3] = n
    Last edited by dr0be; 05-05-2007 at 03:26 PM.

  12. #12
    Registered User
    Join Date
    Sep 2006
    Posts
    8,868
    Quote Originally Posted by dr0be View Post
    Well I was trying to have this...
    Code:
    fscanf(fp, "&#37;c", &fName[i]);
    Assign fName[0] to be 'John'

    Then this...
    Code:
    printf("%c", fName[0]);
    Would print it, but it doesnt seem to be working.

    *EDIT* I printed just the single fName[0] outside of a for statement and it just printed 1 char, so when its being assigned from the file its only assigning 1 char per array value.
    fName[0] = J
    fName[1] = o
    fName[2] = h
    fName[3] = n
    Right you are. %c tells fscanf to get just ONE char, not a whole string. Same with printf - %c tells it to output just one char, not a whole name.

  13. #13
    Registered User
    Join Date
    Mar 2007
    Posts
    19
    Quote Originally Posted by Adak View Post
    Right you are. %c tells fscanf to get just ONE char, not a whole string. Same with printf - %c tells it to output just one char, not a whole name.
    Alright, well I changed the scan and print to %s and the things just crashing again, this is so irritating.

  14. #14
    Math wizard
    Join Date
    Dec 2006
    Location
    USA
    Posts
    582
    Quote Originally Posted by dr0be View Post
    I am using Microsoft Visual C++ 6.0, so I'm not really sure where to turn on warning, id search for it, but something happened with the MSDN when I installed it and I do not have the CD (back at school).
    Set the warning level by doing this (as with VC++ 2005 Express anyway):

    1. Go to project > properties.
    2. Expand the Configuration then C/C++ items then choose the "General" item.
    3. You can see "warning level" on the right side.
    4. Click on the area where the warning level is shown and a drop down menu appears. Choose "level 4" from the group.
    5. Okay it and go to file > save all.
    6. Rebuild (or just click the "test run" button) and you'll see any further warnings.

    It may be a bit difference with VC6.

    If the compiler switches/command lines aren't different, you could add a "/W?" without the quotes and replacing the ? with a number from 0 to 4. I'd suggest 4 for the highest warning level.
    Last edited by ulillillia; 05-05-2007 at 03:48 PM. Reason: Another method added

  15. #15
    Registered User
    Join Date
    Mar 2007
    Posts
    19
    Alright, changed it to 4, and I still get no errors but program crashes when I execute. I got to be doing something wrong with the file or assigning the string values. Heres my current code at the moment.

    Code:
    int main()
    {
    	FILE *fp;
    	char *mode = "r";
    	int i=0;
    	char *fName[MAXNUM], *lName[MAXNUM];
    	int carNum[MAXNUM] = {0}, milesDriven[MAXNUM] = {0}, usedGallons[MAXNUM] = {0};
    	double milesPerGallon[MAXNUM] = {0};
    	int totalMiles = 0, totalGallons = 0;
    	double totalMPG = 0, averageMPG = 0;
    
    	fp = fopen("cars.dat", "r");
    
    	if (fp == NULL) 
    	{
    		printf("Can't open input file cars.dat!\n");
    		exit(1);
    	}
    
    	for (i=0; i<MAXNUM; i++)
    	{
    		fscanf(fp, "&#37;s", &fName[i]);          /**/
    		fscanf(fp, "%s", &lName[i]);          /**/
    		fscanf(fp, "%d", &carNum[i]);         /*Assigns variables from file*/
    		fscanf(fp, "%d", &milesDriven[i]);    /**/
    		fscanf(fp, "%d", &usedGallons[i]);    /**/
    		totalMiles += milesDriven[i];  /*Sums total miles*/
    		totalGallons += usedGallons[i];  /*Sums total gallons*/
    		milesPerGallon[i] = ((double)milesDriven[i] / usedGallons[i]);  /*Calculates MPG*/
    	}
    
    	for (i=0; i<MAXNUM; i++)
    		totalMPG += milesPerGallon[i];  /*Sums total MPG*/
    	averageMPG = (totalMPG / MAXNUM);  /*Calculates Avg MPG*/
    
    	
    	printf("Last_Name   First_Name   Car_No.   Miles_Driven   Gallons_Used   MPG\n");  /*print header*/
    	for (i=0; i<MAXNUM; i++)
    	{
    		printf("%c", fName[i]);
    		printf("%c", lName[i]);	
    		printf("%d", carNum[i]);
    		printf("%d", milesDriven[i]);
    		printf("%d", usedGallons[i]);
    		printf("%d", milesPerGallon[i]);
    		printf("\n");
    	}
    
    
    	fclose(fp);
    	getch();
    
    	return 0;
    }
    The output it is giving me is weird, and the printf's seem right, so im assuming its how im assigning variables from the file. heres the output.

    Code:
    Last_Name   First_Name   Car_No.   Miles_Driven   Gallons_Used   MPG
    JA9723815-1145324612
    M 67350100
    AS9910080
    JJ8812386-1997659207
    TM561000800
    Ms0000
    Last edited by dr0be; 05-05-2007 at 03:58 PM.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. opening empty file causes access violation
    By trevordunstan in forum C Programming
    Replies: 10
    Last Post: 10-21-2008, 11:19 PM
  2. Can we have vector of vector?
    By ketu1 in forum C++ Programming
    Replies: 24
    Last Post: 01-03-2008, 05:02 AM
  3. Game Pointer Trouble?
    By Drahcir in forum C Programming
    Replies: 8
    Last Post: 02-04-2006, 02:53 AM
  4. Possible circular definition with singleton objects
    By techrolla in forum C++ Programming
    Replies: 3
    Last Post: 12-26-2004, 10:46 AM
  5. System
    By drdroid in forum C++ Programming
    Replies: 3
    Last Post: 06-28-2002, 10:12 PM