Help with reading strings and opening files PLEASE

This is a discussion on Help with reading strings and opening files PLEASE within the C Programming forums, part of the General Programming Boards category; I am having a whole lot of trouble so far with this program. The program prompts the user for the ...

  1. #1
    Registered User
    Join Date
    Oct 2008
    Posts
    13

    Help with reading strings and opening files PLEASE

    I am having a whole lot of trouble so far with this program. The program prompts the user for the name of a file, which contains floating point numbers, to be opened for reading and store the values into an array. The rest of the program is done...I think. My problem is that everytime I try to run the program it prints my error message for not being able to open the file and exits. Where did I mess up with the reading of the filename or opening the file or I dont know

    I know the return values for fopen are EOF, NULL and I think 0 or nothing if it works but it still keeps tripping up on the NULL case I guess

    This is one of my first programs and ANY help is much appreciated

    THANKS

    Ive tried many things so far and this is what I have at the moment.....

    Code:
    #include <stdio.h>
    #include <stdlib.h>
    
    #define FLUSH while (fgetc(fileDataIn) != '\n')
    #define MAX_SIZE_NAME 100
    #define MAX_SIZE_FILE 100
    
    
    int main(void)
    {
    float data[MAX_SIZE_FILE];
    char fileName[MAX_SIZE_NAME];
    int fileLength;
    float h;
    int i;
    FILE *fileDataIn;
    int result;
    
    printf("Enter File Name: ");
    scanf("%s", &fileName);
    
    //open file
    fileDataIn = fopen(fileName, "r");
    
    if (fileDataIn == NULL)
    	{
    	printf("Error: Could not open file %s for read.", fileName);
    	exit(1);        
    	} //if
    
    
    	else
             while (fscanf(fileDataIn, "%f", &h) != EOF)
    		{
    		  for (i = 0; result = fscanf(fileDataIn, "%f", &h); i++)
               	  	if (result != 1)
    			{
    			  FLUSH;
    			} //if
    		
    	 	data[i] = h; //should store each value read in into consecutive locations in data
             	fileLength = i + 1;
    
             	} // while
    			
     fclose(fileDataIn);
    
    
    return 0;
    }

  2. #2
    Banned master5001's Avatar
    Join Date
    Aug 2001
    Location
    Visalia, CA, USA
    Posts
    3,685
    >> I know the return values for fopen are EOF, NULL and I think 0 or nothing if it works but it still keeps tripping up on the NULL case I guess

    Not exactly... fopen() either returns a handle or NULL if something went awry.

    This next bit of code is kind of shady. You need to be very careful not to cause buffer overflows when using scanf().

    Code:
      printf("Enter File Name: ");
      scanf("&#37;s", &fileName);
    Instead perhaps you could do something like this:
    Code:
      printf("Enter File Name: ");
      fgets(fileName, sizeof(fileName), stdin);
      strtok(fileName, "\n");
    Moving along to where you confuse me...
    Code:
      for (i = 0; result = fscanf(fileDataIn, "%f", &h); i++)
        if (result != 1)
        {
           FLUSH;
        }
    I don't comprehend your logic there.
    Last edited by master5001; 11-12-2008 at 07:09 PM.

  3. #3
    Registered User
    Join Date
    Oct 2008
    Posts
    13
    Thanks for the quick reply master5001

    I added your ideas with fgets and strtok but still get the same error.

    Could I be saving the .txt file incorrectly?

    For that confusing code part..
    I was trying to increment i, which would control where in data[] the value would be stored. In my head the code should read in a number and store it in h. Then data[i] = h should store those values in different spots as i is incremented. I think if fscanf returns 0 then im trying to flush out the \n from the file to get to the rest of the data.

    The data in the file looks like this

    89
    23.5
    90
    1
    0
    -5.25
    10000
    25123.90
    54321.23
    6
    55
    76
    33
    104
    145
    204
    32
    445
    523
    -2
    -64.6
    3
    76
    33

  4. #4
    Banned master5001's Avatar
    Join Date
    Aug 2001
    Location
    Visalia, CA, USA
    Posts
    3,685
    Code:
    #include <stdio.h>
    #include <stdlib.h>
    #include <string.h>
    
    #define FLUSH while (fgetc(fileDataIn) != '\n')
    #define MAX_SIZE_NAME 100
    #define MAX_SIZE_FILE 100
    
    
    int main(void)
    {
      float data[MAX_SIZE_FILE];
      char fileName[MAX_SIZE_NAME];
      int fileLength = 0;
      float h;
      FILE *fileDataIn;
      int result;
    
      printf("Enter File Name: ");
      fgets(fileName, sizeof(fileName), stdin);
      strtok(fileName, "\n");
    
      //open file
      fileDataIn = fopen(fileName, "r");
    
      if (fileDataIn == NULL)
      {
        printf("Error: Could not open file \"&#37;s\" for read.", fileName);
        return EXIT_FAILURE;
      } //if
      /* else <- Why? */
      while ((result = fscanf(fileDataIn, "%f", &h)) != EOF)
      {
        if (result != 1)
        {
          FLUSH;
        } //if	
        data[fileLength++] = h; //should store each value read in into consecutive locations in data
         
      } // while
    
      fclose(fileDataIn);
      return EXIT_SUCCESS;
    }
    Last edited by master5001; 11-12-2008 at 07:51 PM.

  5. #5
    Banned master5001's Avatar
    Join Date
    Aug 2001
    Location
    Visalia, CA, USA
    Posts
    3,685
    To be honest, I would write a function that counts lines, and create your data buffer dynamically.

    Example:
    Code:
    size_t count_lines(FILE *file)
    {
      size_t n;
      char buffer[4096]; /* 4k should be big enough */
    
      for(n = 0; fgets(buffer, sizeof(buffer), file); ++n)
        ; /* nothing to do here */
    
      rewind(file);
      return n;
    }

  6. #6
    Registered User
    Join Date
    Oct 2008
    Posts
    13
    Hey thanks again
    Im gonna work on this more later. Hopefully it all goes well!

  7. #7
    CSharpener vart's Avatar
    Join Date
    Oct 2006
    Location
    Rishon LeZion, Israel
    Posts
    6,484
    #define FLUSH while (fgetc(fileDataIn) != '\n')
    what will happen with your macro call when the end of file is reached?
    what will happen with your macro in the code like
    Code:
    do
       FLUSH;
    while(condition);
    ?

    what will happen with your macro if the variable fileDataIn will be renamed in the code?
    The first 90% of a project takes 90% of the time,
    the last 10% takes the other 90% of the time.

  8. #8
    Registered User
    Join Date
    Oct 2008
    Posts
    13
    Thanks I got it all working now. Turns out the main problem was how I was saving the file.

    But now I have run into another problem. When I read all of the values into my array I am somehow reading an extra zero. I think it is at the beginning when I store the numbers but im not sure. It adds a zero to my array whenever the file does not even contain a zero.

    Any help would again be great!

    Code:
    #include <stdio.h>   
    #include <stdlib.h>
    #include <string.h>
    
    #define FLUSH while (fgetc(fp) != '\n')
    #define MAX_SIZE_NAME 100
    #define MAX_SIZE_FILE 100
    
    
    
    int main(void)
    {
    // local declarations in main
    
    float data[MAX_SIZE_FILE];
    char fileName[MAX_SIZE_NAME];
    int fileLength = 0;
    float h;
    FILE* fp;
    int result;
            //for sorting
    int current;
    int walker;
    float temp;
            //for printing table
    int numPrinted = 0;
    int j;
            //for average
    int k;
    float sum = 0;
    float average;
            
            
    // first print my name
    printf("\nNAME: Nathan Vazquez\n\n");
            
    
    printf("Enter File Name: ");
    fgets(fileName, sizeof(fileName), stdin);
    strtok(fileName, "\n");
    
    //open file
    fp = fopen(fileName, "r");
    if (fp == NULL)
      {
      printf("Error: Could not open file %s for read.", fileName);
      return EXIT_FAILURE;
      } //if
     while ((result = fscanf(fp, "%f", &h)) != EOF && (fileLength < 100))
            {
              if (result != 1)
               {
                 FLUSH;  
               } //if
    
    
            data[fileLength++] = h;
            
            } // while
    
    //done opening and storing file
    
    
    
    //sort data in file
    for(current = 0; current < fileLength; current++)
            {
            //inner loop: Bubble up one element each pass
       
            for (walker = fileLength; walker > current; walker--) 
      
                    if (data[walker] < data[walker - 1])
                      {
                            temp                    = data[walker];
                            data[walker]            = data[walker - 1];
                            data[walker - 1]        = temp;
                      } //closes if
            } //closes outer for loop
                 
    //print out data 
    printf("\n\n");
    for (j = 0; j < fileLength; j++)
            {
              numPrinted++;
              printf("  %8.2f ", data[j]);
    
            if (numPrinted >= 5)
                    {
                      printf("\n");
                      numPrinted = 0;
                    } //closes if
    
             } // closes for
             
    printf("\n\n"); // provides the one line gap between data table and results
       
    //prints out the number of elements in the file
    printf("There were %d numbers found in file %s\n", fileLength, fileName);
                    
    // Smallest number found
    printf("The smallest number found was: \t%8.2f\n", data[0]);  
    //Largest number found
    printf("The largest number found was: \t%8.2f\n", data[fileLength]);
                 
    for(k = 0; k < fileLength; k++)
            {
              sum = sum + data[k];  
            } //for
              
            average = sum / fileLength;   
    
    printf("The average of the values is: \t%8.2f\n", average);
                     
                      
    fclose(fp);
    return EXIT_SUCCESS;
    
    }

  9. #9
    Banned master5001's Avatar
    Join Date
    Aug 2001
    Location
    Visalia, CA, USA
    Posts
    3,685
    Quote Originally Posted by vart View Post
    what will happen with your macro call when the end of file is reached?
    what will happen with your macro in the code like
    Code:
    do
       FLUSH;
    while(condition);
    ?

    what will happen with your macro if the variable fileDataIn will be renamed in the code?
    Hmmm such things can also result in random crap happening... like I don't know... oh lets say an extra zero....

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Searching for files using strings...
    By legit in forum C++ Programming
    Replies: 6
    Last Post: 06-16-2009, 09:00 AM
  2. Replies: 9
    Last Post: 03-17-2006, 11:44 AM
  3. Question About Reading Files
    By Zildjian in forum C Programming
    Replies: 1
    Last Post: 09-28-2003, 05:31 PM
  4. Reading strings from a file
    By Capulet in forum C Programming
    Replies: 7
    Last Post: 12-04-2002, 03:58 AM
  5. Opening files with variable name?
    By Brown Drake in forum C++ Programming
    Replies: 2
    Last Post: 11-15-2001, 01:32 PM

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21