Thread: Modify text file

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

    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
    
    
    void modifySales()
    {
        FILE *salesPtr; // sales.txt file pointer
        FILE *salesmanPtr; // salesman.txt file pointer
        FILE *tempSalesPtr; // temp.txt file pointer
        int a, 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
        {
            // fopen opens the file; exits program if file cannot be opened
            if ( (salesmanPtr = fopen("salesman.txt","r")) == NULL)
            {
                printf("Cannot open salesman.txt"); // display error message 
                system("pause"); // pause program before it exits
                exit(-1); // end program 
            } // end if
            else
            { 
                tempSalesPtr = fopen("temp.txt","w");
                // prompt and read salesman id
                printf("\nSalesman ID (NO.): ");
                scanf("%d",&modify);
                for(a=0; a<SIZE; a++)
                {
                    // read salesman id from file if there are still have salesman id
                    if ((fscanf(salesPtr,"%[^|]|", salesman[a].id_txt) ) == 1 )
                    {    
                        fprintf(tempSalesPtr,"%s|",salesman[a].id_txt);
                        // read salesman name    
                        //fscanf(salesmanPtr,"%*[^\n]\n%*s\t\t%[^\n]\n%*[^\n]\n%*[^\n]\n%*[^\n]\n\n",salesman[a].name);
                        for (b=0; b<4; b++)
                        {   // read quarterly sales amount     
                            if(b<3)
                            {
                                if (a != modify - 1)
                                {
                                    fscanf(salesPtr,"%lf|", &sale[a][b]);
                                }
                                else
                                {
                                    printf("Quarter %d: ",b+1);
                                    scanf("%lf",&sale[a][b]);
                                }
                                fprintf(tempSalesPtr,"%.2f|",sale[a][b]);
                            }// end if
                            else
                            {
                                if (a != modify - 1)
                                {
                                    fscanf(salesPtr,"%lf\n", &sale[a][b]);
                                }
                                else
                                {
                                    printf("Quarter %d: ",b+1);
                                    scanf("%lf",&sale[a][b]);
                                }
                                fprintf(tempSalesPtr,"%.2f\n",sale[a][b]);
                            }
                            // end else
                        } // end for
                    } // end if
                } // end for 
            } // end else
            fclose(salesPtr); // fclose close the file
        } // end else
        fclose(salesmanPtr); // fclose close the file
        fclose(tempSalesPtr);
        system("pause");
    }
    
    
    // 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 id = 0, lastId, resetId = 0;
    
    
        // 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;
                // call report_menu function
                case 2:
                    break;
                case 3:
                    modifySales();
                    break;
            } // end switch
        }// end while 
        system("pause"); // pause the program before it exits    
        return 0;
    } // end main
    Modify text file-output-jpg

    Why comes out the junk text?
    Attached Files Attached Files

  2. #2
    Registered User
    Join Date
    Jun 2012
    Posts
    127
    Anyone can help me?

  3. #3
    Registered User
    Join Date
    Jun 2012
    Posts
    82
    tidy up your codes please D:

  4. #4
    Registered User
    Join Date
    Sep 2012
    Posts
    357
    Things my compiler noticed:
    * In your function nextId() not all code paths return a value

  5. #5
    Registered User
    Join Date
    May 2012
    Posts
    1,066
    Quote Originally Posted by ulti-killer View Post
    Why comes out the junk text?
    In future posts please provide more information (e.g. what entry do you try to modify) which makes helping you much easier.

    I guess you were modifying the second line in "sales.txt", i.e. "modify" is 2 in your code, right?

    The problem is that when you write out the new values to the file "temp.txt", you don't move forward in the file "sales.txt", i.e. the file you read from. Thus in the following iterations you are out of sync (you are still reading parts of the second line in "sales.txt").

    Bye, Andreas

  6. #6
    Registered User
    Join Date
    Jun 2012
    Posts
    127
    How can I skip and go to next line?

  7. #7
    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 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
    
    
    void modifySales()
    {
        FILE *salesPtr; // sales.txt file pointer
        FILE *salesmanPtr; // salesman.txt file pointer
        FILE *tempSalesPtr; // temp.txt file pointer
        int a, 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
        {
            // fopen opens the file; exits program if file cannot be opened
            if ( (salesmanPtr = fopen("salesman.txt","r")) == NULL)
            {
                printf("Cannot open salesman.txt"); // display error message 
                system("pause"); // pause program before it exits
                exit(-1); // end program 
            } // end if
            else
            { 
                tempSalesPtr = fopen("temp.txt","w");
                // prompt and read salesman id
                printf("\nSalesman ID (NO.): ");
                scanf("%d",&modify);
                for(a=0; a<SIZE; a++)
                {
                    // read salesman id from file if there are still have salesman id
                    if ((fscanf(salesPtr,"%[^|]|", salesman[a].id_txt) ) == 1 )
                    {    
                        fprintf(tempSalesPtr,"%s|",salesman[a].id_txt);
                        // read salesman name    
                        //fscanf(salesmanPtr,"%*[^\n]\n%*s\t\t%[^\n]\n%*[^\n]\n%*[^\n]\n%*[^\n]\n\n",salesman[a].name);
                        for (b=0; b<4; b++)
                        {   // read quarterly sales amount     
                            if(b<3)
                            {
                                if (a != modify - 1)
                                {
                                    fscanf(salesPtr,"%lf|", &sale[a][b]);
                                }
                                else
                                {
                                    printf("Quarter %d: ",b+1);
                                    scanf("%lf",&sale[a][b]);
                                }
                                fprintf(tempSalesPtr,"%.2f|",sale[a][b]);
                            }// end if
                            else
                            {
                                if (a != modify - 1)
                                {
                                    fscanf(salesPtr,"%lf\n", &sale[a][b]);
                                }
                                else
                                {
                                    printf("Quarter %d: ",b+1);
                                    scanf("%lf",&sale[a][b]);
                                }
                                fprintf(tempSalesPtr,"%.2f\n",sale[a][b]);
                            }// end else
                        } // end for
                       if (a == modify - 1)
                      {
                            fscanf(salesPtr,"%*[^\n]\n");
                      }
                    } // end if
                } // end for 
            } // end else
            fclose(salesPtr); // fclose close the file
        } // end else
        fclose(salesmanPtr); // fclose close the file
        fclose(tempSalesPtr);
        system("pause");
    }
    
    
    // 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 id = 0, lastId, resetId = 0;
    
    
        // 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;
                // call report_menu function
                case 2:
                    break;
                case 3:
                    modifySales();
                    break;
            } // end switch
        }// end while 
        system("pause"); // pause the program before it exits    
        return 0;
    } // end main
    I already done it. Thanks to AndiPersti.

  8. #8
    Registered User
    Join Date
    May 2012
    Posts
    1,066
    I would write a loop which reads in one line from the input file, process it if necessary and write the (new) line to the output file.

    Code:
    while (fgets(buffer, sizeof(buffer), input_file) != NULL)
    {
        items_read = sscanf(buffer, "your format string", your variables);
        // check items_read
        if line needs processing
            // do it
            // finish with constructing a new line:
            sprintf(buffer, "your format string", your variables);
        fputs(buffer, output_file);
    }
    if (!feof(input_file))
       // we have a problem
    Bye, Andreas
    Last edited by AndiPersti; 11-05-2012 at 07:32 AM.

  9. #9
    Registered User
    Join Date
    Jun 2012
    Posts
    127
    How to delete temp.txt after I write back the to sales.txt?

  10. #10
    Registered User
    Join Date
    Jun 2012
    Posts
    127
    Code:
    void modifySales(int lastId)
    {
    	FILE *salesPtr; // sales.txt file pointer
    	FILE *salesmanPtr; // salesman.txt file pointer
    	FILE *tempSalesPtr; // temp.txt file pointer
    	int a, b, modify; // counter 
    	double sale[SIZE][4]; // quartely sales amount
    	char oldname[] = "tempSales.txt"; // old file name
    	char newname[] = "sales.txt"; // new file name
    
    
    	// 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
    	{
    		// fopen opens the file; exits program if file cannot be opened
    		if ( (salesmanPtr = fopen("salesman.txt","r")) == NULL)
    		{
    			printf("Cannot open salesman.txt"); // display error message 
    			system("pause"); // pause program before it exits	
    			exit(-1); // end program 
    		} // end if
    		else
    		{ 
    			tempSalesPtr = fopen("tempSales.txt","w");
    			// prompt and read salesman id
    			printf("\nSalesman ID (NO.): ");
    			scanf("%d",&modify);
    
    
    			// read salesman id from file if there are still have salesman id
    			for(a=0; a<lastId && fscanf(salesPtr,"%[^|]|", salesman[a].id_txt); a++)
    			{
    				// write salesman id to text file
    				fprintf(tempSalesPtr,"%s|",salesman[a].id_txt);
    				//printf("%s", salesman[a].id_txt);
    			
    					// read salesman name	
    					//fscanf(salesmanPtr,"%*[^\n]\n%*s\t\t%[^\n]\n%*[^\n]\n%*[^\n]\n%*[^\n]\n\n",salesman[a].name);
    					for (b=0; b<4; b++)
    					{   
    						// read quarterly sales amount
    						// end with "|" symbol if b is less than 3
    						if(b<3)
    						{
    							// if it is not required salesman id; read from text file   
    							if (a != modify - 1 )
    							{
    								fscanf(salesPtr,"%lf|", &sale[a][b]);
    							} // end if 
    							else
    							{
    								printf("Quarter %d: ", b+1);
    								scanf("%lf",&sale[a][b]);
    							} // end else
    							fprintf(tempSalesPtr,"%.2f|",sale[a][b]);
    						}// end if
    						// end with newline 
    						else
    						{
    							if (a != modify - 1 )
    							{
    								fscanf(salesPtr,"%lf\n", &sale[a][b]);
    							}
    							else
    							{
    								printf("Quarter %d: ", b+1);
    								scanf("%lf",&sale[a][b]);
    							}
    							fprintf(tempSalesPtr,"%.2f\n",sale[a][b]);
    						}// end else
    					} // end for
    					if (a == modify - 1)
    					{
    						fscanf(salesPtr,"%*[^\n]\n");
    					}
    			} // end for 
    		} // end else
    		fclose(salesPtr); // fclose close the file
    	} // end else
    	fclose(salesmanPtr); // fclose close the file
    	fclose(tempSalesPtr);
    	
    	remove("sales.txt");
    	rename(oldname,newname);
    }
    Finally. I did it in this way.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Modify text file
    By ulti-killer in forum C Programming
    Replies: 3
    Last Post: 10-13-2012, 12:14 PM
  2. Replies: 3
    Last Post: 05-25-2011, 05:54 PM
  3. 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
  4. any way to modify static text? lol
    By jverkoey in forum Windows Programming
    Replies: 3
    Last Post: 04-27-2003, 06:34 AM
  5. Can't modify the text in
    By Magos in forum Windows Programming
    Replies: 3
    Last Post: 08-15-2002, 03:27 PM