using r+ to modify text file

This is a discussion on using r+ to modify text file within the C Programming forums, part of the General Programming Boards category; Code: #include <stdio.h> #include <stdlib.h> #include <string.h> // number of salesman #define SIZE 100 // salesman_type structure definition typedef struct{ ...

  1. #1
    Registered User
    Join Date
    Jun 2012
    Posts
    127

    using r+ to modify text file

    Code:
    #include <stdio.h>
    #include <stdlib.h>
    #include <string.h>
    
    
    
    
    // number of salesman 
    #define SIZE 100
    // salesman_type structure definition
    typedef struct{
    		int ID; // salesman id
    		char id_txt[6]; // salesman id for txt file
    		char name[50]; // salesman name
    		double hor_total; // total sales amount of a salesman  
    	}salesman_type; // end structure salesman_type
    
    
    salesman_type salesman[SIZE];// synonym for salesman_type 
    
    
    // function prototype
    int nextId(int currentId, int isReset);
    int sale_menu(); 
    void modifySales();
    
    
    
    
    // function to generate id
    // currentId and isReset are parameters
    int nextId(int currentId, int isReset)
    {
    	// initializes elements to 0 for the first time function is called
    	static int lastId = 0;
    	// if isReset is 0, assign currentId to lastId;
    	if (isReset == 0)
    	{
    		lastId = currentId;
    	}
    	//if isReset is not 0, return and add 1 to lastId 
    	if (isReset != 0)
    		return ++lastId;
    } // end function nextId
    
    
    // sales processing system menu function
    int sale_menu()
    {
    	int menu;
    	system("cls");
    	printf("Sales Processing System\n");
    	printf("-----------------------\n\n");
    	printf("1. Add Salesman Records\n");
    	printf("2. Reports Generation\n");
    	printf("3. Modify Salesman Records\n");
    	printf("4. Delete Salesman Records\n\n");
    	printf("0. Exit\n");
    	printf("Your choice: ");
    	scanf("%d", &menu);
    	return menu;
    	printf("\n");
    }// end function sale_menu
    
    
    // modify salesman records function 
    void modifySales()
    {
    	FILE *salesPtr; // sales.txt file pointer
    	FILE *salesmanPtr; // salesman.txt file pointer
    	int a = 1, b, modify; // counter 
    	double sale[SIZE][4]; // quartely sales amount
    
    
    	// fopen opens the file; exits program if file cannot be opened
    	if ( (salesPtr = fopen("sales.txt","r+")) == NULL )
    	{
    		printf("Cannot open sales.txt\n"); // display error message 
    		system("pause"); // pause program before it exits
    		exit(-1); // end program 
    	} // end if
    	else
    	{
    		// prompt and read salesman id
    		printf("\nSalesman ID (NO.): ");
    		scanf("%d",&modify);
    
    
    		// if it is not required salesman id
    		while (a != modify)
    		{
    			fscanf(salesPtr,"%*[^\n]\n");
    			a++;
    		}
    
    
    		fscanf(salesPtr,"%*[^|]|", salesman[0].id_txt);
    		// read quarterly sales amount
    		for (b=0; b<4; b++)
    		{   
    			// prompt and read quarterly sales amount
    			printf("Quarter %d: ", b+1);
    			scanf("%lf",&sale[0][b]);
    			// end with "|" symbol if b is less than 3
    			if(b<3)
    			{
    				fprintf(salesPtr,"%.2f|",sale[0][b]);
    			}
    			else
    			{
    				fprintf(salesPtr,"%.2f\n",sale[0][b]);
    			}
    		} // end for
    	} // end else
    	fclose(salesPtr); // fclose close the file
    } // end function modifySales 
    
    
    // function main begins program execution
    int main()
    {
    	// nextid.txt file pointer 
    	FILE *readIdPtr;
    	// variable declaration
    	int a, b, c = 0, last; // counter
    	int getMenu = 10, getReport = 10; // menu selector
    	double ver_total = 0, max = 0; 
    	int lastId; // last saved salesman id
    	int resetId = 0; // pass value execute assignment of nextId function
    
    
    	// fopen opens the file; exits program if file cannot be opened
    	if ( (readIdPtr = fopen("nextid.txt","r") ) == NULL)
    	{
    		printf("Cannot open nextid.txt file\n");
    		system("pause");
    		exit(-1);
    	} // end if
    	else
    	{
    		// read lastId from file
    		fscanf(readIdPtr,"%d",&lastId);
    		// Generate new id from previous salesman ID if the salesman is one or more
    		// lastId and restId are arguments
    		nextId(lastId, resetId);
    	} // end else
    	// fclose close the file
    	fclose(readIdPtr);
    	printf("\n");
    	
    	while (getMenu != 0)
    	{
    		// call and assign sale_menu function to getMenu
    		// Execute command based on user input
    		switch(getMenu = sale_menu())
    		{
    			case 1:
    				break;
    			case 2:
    				break;
    			case 3:
    				modifySales(lastId);
    				break;
    		} // end switch
    	}// end while 
    	return 0;
    } // end main
    I expect the first salesman of quarterly sales amount all change to 1 but it didn't. What's wrong with my code?
    Attached Files Attached Files

  2. #2
    SAMARAS std10093's Avatar
    Join Date
    Jan 2011
    Location
    Nice, France
    Posts
    2,675
    While trying to reach the point that you use r+,i spotted this line of code
    Code:
    nextId(lastId, resetId);
    You understand that this has no effect.You do not pass the variable as a reference,neither you collect it main when returned.Maybe this is not what you want to happen.Perhaps, you were for something like this( if for example myVar is the value you wish to be returned)
    Code:
    id = nextId(lastId, resetId);

  3. #3
    Registered User
    Join Date
    Jun 2012
    Posts
    127
    Quote Originally Posted by std10093 View Post
    While trying to reach the point that you use r+,i spotted this line of code
    Code:
    nextId(lastId, resetId);
    You understand that this has no effect.You do not pass the variable as a reference,neither you collect it main when returned.Maybe this is not what you want to happen.Perhaps, you were for something like this( if for example myVar is the value you wish to be returned)
    Code:
    id = nextId(lastId, resetId);
    Ignore that staff, I design for other purpose.

  4. #4
    Registered User
    Join Date
    Jun 2012
    Posts
    127
    Code:
    #include <stdio.h>
    #include <stdlib.h>
    #include <string.h>
    
    
    
    
    // number of salesman 
    #define SIZE 100
    // salesman_type structure definition
    typedef struct{
    		int ID; // salesman id
    		char id_txt[6]; // salesman id for txt file
    		char name[50]; // salesman name
    		double hor_total; // total sales amount of a salesman  
    	}salesman_type; // end structure salesman_type
    
    
    salesman_type salesman[SIZE];// synonym for salesman_type 
    
    
    // function prototype
    int sale_menu(); 
    void modifySales();
    
    
    // sales processing system menu function
    int sale_menu()
    {
    	int menu;
    	system("cls");
    	printf("Sales Processing System\n");
    	printf("-----------------------\n\n");
    	printf("1. Add Salesman Records\n");
    	printf("2. Reports Generation\n");
    	printf("3. Modify Salesman Records\n");
    	printf("4. Delete Salesman Records\n\n");
    	printf("0. Exit\n");
    	printf("Your choice: ");
    	scanf("%d", &menu);
    	return menu;
    	printf("\n");
    }// end function sale_menu
    
    
    // modify salesman records function 
    void modifySales()
    {
    	FILE *salesPtr; // sales.txt file pointer
    	FILE *salesmanPtr; // salesman.txt file pointer
    	int a = 1, b, modify; // counter 
    	double sale[SIZE][4]; // quartely sales amount
    
    
    	// fopen opens the file; exits program if file cannot be opened
    	if ( (salesPtr = fopen("sales.txt","r+")) == NULL )
    	{
    		printf("Cannot open sales.txt\n"); // display error message 
    		system("pause"); // pause program before it exits
    		exit(-1); // end program 
    	} // end if
    	else
    	{
    		// prompt and read salesman id
    		printf("\nSalesman ID (NO.): ");
    		scanf("%d",&modify);
    
    
    		// if it is not required salesman id
    		while (a != modify)
    		{
    			fscanf(salesPtr,"%*[^\n]\n");
    			a++;
    		}
    
    
    		fscanf(salesPtr,"%*[^|]|", salesman[0].id_txt);
    		// read quarterly sales amount
    		for (b=0; b<4; b++)
    		{   
    			// prompt and read quarterly sales amount
    			printf("Quarter %d: ", b+1);
    			scanf("%lf",&sale[0][b]);
    			// end with "|" symbol if b is less than 3
    			if(b<3)
    			{
    				fprintf(salesPtr,"%.2f|",sale[0][b]);
    			}
    			else
    			{
    				fprintf(salesPtr,"%.2f\n",sale[0][b]);
    			}
    		} // end for
    	} // end else
    	fclose(salesPtr); // fclose close the file
    } // end function modifySales 
    
    
    // function main begins program execution
    int main()
    {
    	// variable declaration
    	int a, b, c = 0, last; // counter
    	int getMenu = 10, getReport = 10; // menu selector
    	
    	while (getMenu != 0)
    	{
    		// call and assign sale_menu function to getMenu
    		// Execute command based on user input
    		switch(getMenu = sale_menu())
    		{
    			case 1:
    				break;
    			case 2:
    				break;
    			case 3:
    				modifySales();
    				break;
    		} // end switch
    	}// end while 
    	return 0;
    } // end main
    Removed nextId function.
    Attached Files Attached Files

  5. #5
    SAMARAS std10093's Avatar
    Join Date
    Jan 2011
    Location
    Nice, France
    Posts
    2,675
    Code:
    fscanf(salesPtr,"%*[^\n]\n")
    third argument missing.Maybe you should take a second thought for it.

    fscanf

  6. #6
    Registered User
    Join Date
    May 2012
    Posts
    1,066
    Quote Originally Posted by ulti-killer View Post
    I expect the first salesman of quarterly sales amount all change to 1 but it didn't. What's wrong with my code?
    You should already know that "but it didn't" isn't a very useful description for what went wrong. What output did you expected and what output did you get? We don't need screenshots, just write it in plain text.

    Additionally, your idea of opening the file with "r+" so that you can read and write to it at the same time isn't as easy as you thought. Here is the relevant part from the C99 standard (7.19.5.3):
    6 When a file is opened with update mode ('+' as the second or third character in the above list of mode argument values), both input and output may be performed on the associated stream. However, output shall not be directly followed by input without an intervening call to the fflush function or to a file positioning function (fseek, fsetpos, or rewind), and input shall not be directly followed by output without an intervening call to a file positioning function, unless the input operation encounters end-of-file. Opening (or creating) a text file with update mode may instead open (or create) a binary stream in some implementations.
    Your way of writing immediately after reading is undefined behaviour.

    Bye, Andreas

  7. #7
    Registered User
    Join Date
    Jun 2012
    Posts
    127
    S0001|1.00|1.00|1.00|1.00
    S0002|29080.10|30450.00|28950.40|35637.85

    I wan get something like this. User can modify the salesman record based on salesman id such as salesman no.1 that the all the quarterly sales amounts are change to 1.
    Last edited by ulti-killer; 11-06-2012 at 08:05 AM.

  8. #8
    and the hat of wrongness Salem's Avatar
    Join Date
    Aug 2001
    Location
    The edge of the known universe
    Posts
    32,452
    > fscanf(salesPtr,"%*[^|]|", salesman[0].id_txt);
    ...
    > fprintf(salesPtr,"%.2f|",sale[0][b]);
    This does NOT work on text files.

    If your text file contains
    Hello\n
    World\n


    And you come along later, and try to overwrite "Hello\n" with "Banana\n", then part of "World\n" is going to get trashed.

    File update only works for fixed-length records, such as those generated using fread/fwrite.

    For a text file / variable length records, your only choice is to rewrite the file from scratch each time you make a change.
    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.
    I support http://www.ukip.org/ as the first necessary step to a free Europe.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Modify text file
    By ulti-killer in forum C Programming
    Replies: 9
    Last Post: 11-05-2012, 08:38 AM
  2. Modify text file
    By ulti-killer in forum C Programming
    Replies: 3
    Last Post: 10-13-2012, 12:14 PM
  3. Replies: 3
    Last Post: 05-25-2011, 05:54 PM
  4. how can i modify a text in a file
    By Marth in forum C Programming
    Replies: 6
    Last Post: 05-05-2005, 05:08 AM
  5. Can't modify the text in
    By Magos in forum Windows Programming
    Replies: 3
    Last Post: 08-15-2002, 03:27 PM

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