Thread: File reading program not working

  1. #1
    Registered User
    Join Date
    Feb 2012
    Posts
    116

    File reading program not working

    Hi everyone im getting real problems getting a file reading program to work. Here is the file reading function, if i comment it out, the program runs fine so I know this is the "offending" function. Ive included the errors too. If anyone is able to spot whats making it error your help would be much appreciated. i picked up some sloppy programming habbits so maybe there is some better practice things also which id like to improve hopefully so any constructive criticism will be appreciated. thankyou

    Code:
    { //------------------------------------------------------------< Extracting Data from textfile and putting them in order > 
    	int loop;
    	int numberOfReadings;
    	int signalOutput;
    	int flag;
    	int column1;
    	float column2;
    	float temperatureArray[10];
    	srand(time(NULL));
    	FILE *fp;	
    	
    	printf("\n\n The sensor readings and their corresponding temperatures:\n");
    	
    		fp = fopen("LOOKUP.txt", "r");
    		
    		for(loop=0; loop<numberOfReadings; loop++)
    		{
    			signalOutput = (int)(rand()%15);
    			
    			for(flag=0; flag=1; 0)
    			{
    				fscanf(fp, "%i %f",&column1, &column2);
    				
    				if ( signalOutput > column1 ) 
    				{
    					temperatureArray[loop] = column2;
    					flag = 1;
    					printf("\n se %i = %f", signalOutput, temperatureArray[loop]);
    				}			
    			}
    		}
    			
    		
    		fclose(fp);
    }

    1>------ Build started: Project: Assignment 3, Configuration: Debug Win32 ------
    1> Assignment 3.c
    1>c:\users\david baratheon\documents\visual studio 2010\projects\assignment 3\assignment 3\assignment 3.c(34): warning C4013: 'welcome' undefined; assuming extern returning int
    1>c:\users\david baratheon\documents\visual studio 2010\projects\assignment 3\assignment 3\assignment 3.c(35): warning C4996: 'scanf': This function or variable may be unsafe. Consider using scanf_s instead. To disable deprecation, use _CRT_SECURE_NO_WARNINGS. See online help for details.
    1> c:\program files (x86)\microsoft visual studio 10.0\vc\include\stdio.h(304) : see declaration of 'scanf'
    1>c:\users\david baratheon\documents\visual studio 2010\projects\assignment 3\assignment 3\assignment 3.c(76): warning C4996: 'scanf': This function or variable may be unsafe. Consider using scanf_s instead. To disable deprecation, use _CRT_SECURE_NO_WARNINGS. See online help for details.
    1> c:\program files (x86)\microsoft visual studio 10.0\vc\include\stdio.h(304) : see declaration of 'scanf'
    1>c:\users\david baratheon\documents\visual studio 2010\projects\assignment 3\assignment 3\assignment 3.c(85): warning C4996: 'scanf': This function or variable may be unsafe. Consider using scanf_s instead. To disable deprecation, use _CRT_SECURE_NO_WARNINGS. See online help for details.
    1> c:\program files (x86)\microsoft visual studio 10.0\vc\include\stdio.h(304) : see declaration of 'scanf'
    1>c:\users\david baratheon\documents\visual studio 2010\projects\assignment 3\assignment 3\assignment 3.c(25): warning C4101: 'inputError' : unreferenced local variable
    1>c:\users\david baratheon\documents\visual studio 2010\projects\assignment 3\assignment 3\assignment 3.c(28): warning C4101: 'pointers' : unreferenced local variable
    1>c:\users\david baratheon\documents\visual studio 2010\projects\assignment 3\assignment 3\assignment 3.c(127): warning C4244: 'function' : conversion from 'time_t' to 'unsigned int', possible loss of data
    1>c:\users\david baratheon\documents\visual studio 2010\projects\assignment 3\assignment 3\assignment 3.c(128): error C2275: 'FILE' : illegal use of this type as an expression
    1> c:\program files (x86)\microsoft visual studio 10.0\vc\include\stdio.h(66) : see declaration of 'FILE'
    1>c:\users\david baratheon\documents\visual studio 2010\projects\assignment 3\assignment 3\assignment 3.c(128): error C2065: 'fp' : undeclared identifier
    1>c:\users\david baratheon\documents\visual studio 2010\projects\assignment 3\assignment 3\assignment 3.c(132): error C2065: 'fp' : undeclared identifier
    1>c:\users\david baratheon\documents\visual studio 2010\projects\assignment 3\assignment 3\assignment 3.c(132): warning C4047: '=' : 'int' differs in levels of indirection from 'FILE *'
    1>c:\users\david baratheon\documents\visual studio 2010\projects\assignment 3\assignment 3\assignment 3.c(140): error C2065: 'fp' : undeclared identifier
    1>c:\users\david baratheon\documents\visual studio 2010\projects\assignment 3\assignment 3\assignment 3.c(140): warning C4047: 'function' : 'FILE *' differs in levels of indirection from 'int'
    1>c:\users\david baratheon\documents\visual studio 2010\projects\assignment 3\assignment 3\assignment 3.c(140): warning C4024: 'fscanf' : different types for formal and actual parameter 1
    1>c:\users\david baratheon\documents\visual studio 2010\projects\assignment 3\assignment 3\assignment 3.c(152): error C2065: 'fp' : undeclared identifier
    1>c:\users\david baratheon\documents\visual studio 2010\projects\assignment 3\assignment 3\assignment 3.c(152): warning C4047: 'function' : 'FILE *' differs in levels of indirection from 'int'
    1>c:\users\david baratheon\documents\visual studio 2010\projects\assignment 3\assignment 3\assignment 3.c(152): warning C4024: 'fclose' : different types for formal and actual parameter 1
    ========== Build: 0 succeeded, 1 failed, 0 up-to-date, 0 skipped ==========

  2. #2
    Registered User
    Join Date
    Jun 2005
    Posts
    6,815
    Firstly, your reasoning that this is the offending code is invalid. Commenting out some code, and then having your program appear to work, simply suggests there is some interaction between the code you commented out and the code left behind. It does not mean the commented code is the source of the problem.

    Second, because you have only shown a code fragment, the information you have provided is meaningless. There is no correlation between line numbers mentioned in error/warning messages and the code you have shown. The only way anyone can make the connection is by reading your mind telepathically. Few forum members are telepathic.

    Looking at your code - as shown - I can point out a few obvious problems. In the for loop "for (loop = 0; loop<numberOfReadings; loop++) ...." numberOfReadings is uninitialised, and its value never changes in the loop. If an int is uninitialised, its value is indeterminate .... it could be zero, it could be 25000, it could be any other value. Strictly speaking, your program could crash simply by accessing the value of numberOfReadings (as accessing the value of an uninitialised variable gives undefined behaviour, according to the C standard). Since temperatureArray has only 10 elements, the code will tromp random areas of memory if numberOfReadings happens to exceed 10.

    From the error and warning messages, it appears the compiler does not know what FILE is. That suggests you have neglected to #include <stdio.h> in your code.


    In future, don't presume that you know where the problem is. Instead, create a small but complete sample of compilable code that exhibits your actual problem. And report the error messages corresponding to that small and complete sample of code. That way, other folks have some chance of recreating your problem, and giving you useful advice. Rather than, as you have done, playing "blind mans bluff", which forces people to guess what the problem might be.
    Right 98% of the time, and don't care about the other 3%.

    If I seem grumpy or unhelpful in reply to you, or tell you you need to demonstrate more effort before you can expect help, it is likely you deserve it. Suck it up, Buttercup, and read this, this, and this before posting again.

  3. #3
    Registered User
    Join Date
    Feb 2012
    Posts
    116
    well you told me the code i provided was meaningless and couldnt tell you anything and then you proceeded to tell me whats wrong with you code lol

    Ill let you off as the preceeding part was helpful though lol

    Its an assignment so I cant provide the whole code, but im sure the problem lays here

    I do have #include <stdio.h> in my preprocessing directives, can you think of any other reason why it doesnt like this?

    I take your point on producing a small program that includes the code though but last time i did that everyone asked whats the point in the program rather than just helping me with whats wrong with the actual programming aspect lol so I cant win. I do try to post it in a way that wont jeopardise my studies whilst not invoking the irk of the forum but it seems some people love a good moan

    so your basically saying from what you can see from the code i provided, it should work, ive not utilised the file access techniques incorrectly?

    ill try constructing a small program that gives full context to the code but it does seem that its very difficult to find a way to post here without people finding some way of getting onto their high horse and moaning. There should be some agreed ettiquette on how to post a problem so that noone is allowed to moan and is only allowed to post actual help with the programming problem

  4. #4
    Registered User
    Join Date
    Feb 2012
    Posts
    116
    ok here is an attempt at a mock code to give it some context. Please dont ask what the point of the program is as the whole point is getting it to work, its not supposed to be useful, its for learning programming purposes rather than having a practical use. How do I pass the readings and temperature array to the readingFunction, then get the reading function to take random readings from the text file based on the value of readings, then run the function [readings] number of times, getting data from a text file that looks something along the lines of and returns back a set of values to the main function stored in the array?

    1 2.5
    2 5
    3 7.5
    4 15
    5 20
    etc....

    Code:
    #include <stdio.h>
    #include <math.h>
    #include <stdlib.h>
    #include <time.h>
    
    
    float readingFunction(void);
    
    
    int main(void)
    {		
    	int readings;
    	float temperatureArray[readings];
    
    
    	printf("how many readings would you like to take?\n");
    	scanf("%i", &readings);
    
    
    	readingFunction();              // Gives the user a set of readings
    	
    	fflush(stdin);
    	getchar();
    
    
    	return 0;
    } 
    
    
    
    
    float readingFunction(void)
    {
    	int loop;
    	int numberOfReadings;
    	int signalOutput;
    	int flag;
    	int column1;
    	float column2;
    	float temperatureArray[10];
    	srand(time(NULL));
    	FILE *fp;	
    	
    	printf("\n\n The sensor readings and their corresponding temperatures:\n");
    	
    		fp = fopen("LOOKUP.txt", "r");
    		
    		for(loop=0; loop<numberOfReadings; loop++)
    		{
    			signalOutput = (int)(rand()%15);
    			
    			for(flag=0; flag=1; 0)
    			{
    				fscanf(fp, "%i %f",&column1, &column2);
    				
    				if ( signalOutput > column1 ) 
    				{
    					temperatureArray[loop] = column2;
    					flag = 1;
    					printf("\n se %i = %f", signalOutput, temperatureArray[loop]);
    				}			
    			}
    		}
    			
    		
    		fclose(fp);
    }

  5. #5
    Registered User
    Join Date
    May 2010
    Posts
    4,632
    How do I pass the readings and temperature array to the readingFunction
    By passing them as parameters into the function.

    Unless you are using a C99 enabled compiler you may have a problem with the following snippet.
    int readings;
    float temperatureArray[readings];
    Only a C99 compiler guarantees that VLA are valid . C90 does not allow VLA and C11 VLAs are optional. So I recommend using a compile time constant for the size of your array.

    Using fflush() on an input stream is also not recommended, this function is only defined in the standard to work on output streams.

    The srand() function should only be called once, so you should move this call to early in main().

    You should also always check that fopen() succeeded in properly opening your file, and that your fscanf() actually read the proper number of values from your file.

    Jim

  6. #6
    Registered User
    Join Date
    Feb 2012
    Posts
    116
    thanks jim, excellent help

    could you explain a little further whats wrong with the readings and array? I know its problematic as my visual studios doesnt like it but im confused as to why. it should work surely?

    what is a better alternative to fflush()?

    if i call srand() only once, will i still be able to generate many random numbers that differ each time? what exactly does the srand do?

    the fopen was working before and then stopped working when i fiddled around with the code to get it to do what i need

    thanks jim for your help

  7. #7
    Registered User
    Join Date
    Feb 2012
    Posts
    116
    also whats the best practice for passing the variables into the function? Should i use pointers? How do I syntax that?

  8. #8
    Registered User
    Join Date
    May 2010
    Posts
    4,632
    what is a better alternative to fflush()?
    You may want to read the article from the FAQ.
    if i call srand() only once, will i still be able to generate many random numbers that differ each time? what exactly does the srand do?
    Yes. The srand() call seeds the random number generator. If you never seed the generator, or seed the generator with the same "seed" then your sequence will always start at the same number.
    the fopen was working before and then stopped working when i fiddled around with the code to get it to do what i need
    That's why you should always check that your file is opening correctly.
    could you explain a little further whats wrong with the readings and array? I know its problematic as my visual studios doesnt like it but im confused as to why. it should work surely?
    If you are using the old outdated Microsoft compiler* then you can not use Variable Length Arrays (VLA). Microsoft does not support either the C99 or C11 standard so you must use a compile time constant when declaring arrays. Also you must always initialize your variables before you use them. What value does readings contain when you try to declare your array? To solve your problems with the array I recommend defining the size of the array outside any function.
    Code:
    #define ArraySize 10
    
    int main(void)
    {
       int yourArray[ArraySize];
    * I consider any version of the Microsoft C compiler either old or outdated because Microsoft refuses to support the current C standards. The C++ compiler is somewhat better.


    Jim

  9. #9
    Registered User
    Join Date
    Feb 2012
    Posts
    116
    Can the user specify the legnth of the array though as opposed to a fixed 10?

    It seems to be the file bit that it has issues with

    If srand is a local variable in main will it still work in other functions?

  10. #10
    Registered User
    Join Date
    May 2010
    Posts
    4,632
    Can the user specify the legnth of the array though as opposed to a fixed 10?
    Yes, if you use dynamic memory (malloc/free).

    If srand is a local variable in main will it still work in other functions?
    srand() is a function not a variable.

    Jim

  11. #11
    Registered User
    Join Date
    Feb 2012
    Posts
    116
    So if i run srand in main i cam still get random numbrrs in a function?

  12. #12
    Registered User
    Join Date
    May 2010
    Posts
    4,632
    Yes.

  13. #13
    Registered User
    Join Date
    Feb 2012
    Posts
    116
    Ive made all the changes and it still doesnt work.

    It doesnt seem to like the file pointer

    Ive made a basic program but im txting from an iphone so will post up code when im on a pc again.

    Can anyone see a problem with the way ive used file function?

  14. #14
    Registered User claudiu's Avatar
    Join Date
    Feb 2010
    Location
    London, United Kingdom
    Posts
    2,094
    This might be a silly question, but problems like yours generally tend to have an equally silly resolution, but are you certain that your LOOKUP.txt file is where it should be (i.e. wherever VS is building your program)? Furthermore, are you testing the return value of fopen() to ensure that the file is actually opened?
    1. Get rid of gets(). Never ever ever use it again. Replace it with fgets() and use that instead.
    2. Get rid of void main and replace it with int main(void) and return 0 at the end of the function.
    3. Get rid of conio.h and other antiquated DOS crap headers.
    4. Don't cast the return value of malloc, even if you always always always make sure that stdlib.h is included.

  15. #15
    Registered User
    Join Date
    Feb 2012
    Posts
    116
    Hi claudiu

    No such thing as a silly question, any help is useful. Lookup.txt is in the same folder as the program

    I didnt check its return as the program wont run. The error message indicates it has an issue with file and fp

    Kind regards

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Reading a file not working
    By dabbertorres in forum C++ Programming
    Replies: 5
    Last Post: 01-21-2011, 04:31 PM
  2. why .exe file is not working in windows of c program
    By suryak in forum C Programming
    Replies: 9
    Last Post: 01-07-2011, 12:23 PM
  3. reading file then if statement not working
    By patrink in forum C Programming
    Replies: 3
    Last Post: 12-17-2010, 01:48 AM
  4. my serial port data reading program isn't working
    By gnychis in forum C Programming
    Replies: 5
    Last Post: 06-02-2005, 08:40 AM
  5. Getting the name of a file reading to program
    By DarkAbyss in forum C++ Programming
    Replies: 1
    Last Post: 03-22-2003, 10:14 AM