Click here to Skip to main content
15,889,865 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
I have this code and I try to replace a line in a file.txt with a new line..

C++
/// Modify a line in a file.txt ///

#include <stdio.h>
#include <conio.h>
#include <windows.h>

#define KEY_UP 72
#define KEY_DOWN 80
#define KEY_ENTER 13

#define MAX 256
#define ARRAYSIZE(sel) (sizeof(sel) / sizeof(sel[0]))
#define SELECT_END 2

struct Info
{
    char name[50];
    char lastname[50];
    char city[50];
    char country[50];
    char tel[20];
}info;

void menu();
void selector(unsigned int select);
void modifyData();
void printFile(FILE *fptr1);
void hideCursor();

int main()
{
    hideCursor();
	menu();

	return 0;
}

void menu()
{
	int select = 0;
    int x;

    selector(select);

    while((x = getch()))
    {
        if(x == KEY_UP)
        {
            select -= 2;
            if(select < 0)
                select = 0;
            selector(select);
        }
        else if(x == KEY_DOWN)
        {
            select += 2;
            if (select > SELECT_END)
                select = SELECT_END;
            selector(select);
        }
        else if(x == KEY_ENTER)
        {
            if(select <= 1)
            {
                modifyData();
				selector(select);
            }
            else if(select <= 2)
            {
                printf("\n\n\n\n\t\t\t    Exiting Data Base");
                Sleep(1000);
                system("cls");
                exit(0);
            }
        }
    }
}

void selector(unsigned int select)
{
	const char *selections[] =
    {
        "\n\n\n\n\n\t1. >  Modify info",
        "\n\n\n\n\n\t1.    Modify info",
        "\t2. >  Exit Data Base",
        "\t2.    Exit Data Base",
    };
    unsigned int i;

    system("cls");
    printf("\n\t\t\t\tData Base\n\t\t\t\t---------");
    printf("\n\n\n\n\n   Select an option using UP and DOWN arrows then press ENTER");

    for(i = 0; i < ARRAYSIZE(selections); i += 2)
    {
        if(i == select)
            printf ("%s\n", selections[i]);
        else
            printf ("%s\n", selections[i + 1]);
    }
}

void modifyData()
{
	FILE *fptr1, *fptr2;
	int newLine;
	char data1[MAX] = "records.txt";
	char data2[MAX];

	system("cls;");
	printf("\n\t\t\t\tData Base\n\t\t\t\t---------");
	printf("\n\n   Replace old info");
	printf("\n   ----------------");


	fptr1 = fopen(data1, "r");
	fptr2 = fopen("temp.txt", "w");

	while(1)
	{
		if(fptr1 == NULL || fptr2 == NULL)
		{
			printf("\n\n\n   Unable to open the input file\n\a");
			Sleep(1000);
			printf("\n   %s", strerror(errno));
			Sleep(1500);
			fclose(fptr1);
			fclose(fptr2);
			remove("temp.txt");
			break;
		}

		fseek(fptr1, 0, SEEK_END);
		long size = ftell(fptr1);
		if(size == 0)
		{
			printf("\n\n   No information in data base\a");
			Sleep(1500);
			fclose(fptr1);
			fclose(fptr2);
			remove("temp.txt");
			break;
		}

		system("cls;");
		printf("\n\t\t\t\tData Base\n\t\t\t\t---------");
		printf("\n\n   Replace old info");
		printf("\n   ----------------\n\n");

		printFile(fptr1);

		fseek(fptr1, 0, SEEK_SET);

		printf("\n\n\n   Update the old info with the following:");
		printf("\n\n\n   New Info");

        printf("\n\n\n\tName:       ");
        scanf("%49s", info.name);
        printf("\n\n\tLast name:  ");
        scanf("%49s", info.lastname);
        printf("\n\n\tCity:       ");
        scanf("%49s", info.city);
        printf("\n\n\tCountry:    ");
        scanf("%49s", info.country);
        printf("\n\n\tPhone:      ");
        scanf("%19s", info.tel);

        fprintf(fptr2, "%s %s %s %s %s\n", info.name, info.lastname, info.city, info.country, info.tel);

        fgets(data2, MAX, stdin);

		printf("\n\n\n   Input the line number you want to replace:  ");
		scanf("%i", &newLine);

		for (int lineCtr = 1; fgets(data1, MAX, fptr1) != NULL; ++lineCtr)
		{
			fprintf(fptr2, "%s", lineCtr != newLine ? data1 : data2);
		}

		fclose(fptr1);
		fclose(fptr2);
		remove("records.txt");
		rename("temp.txt", "records.txt");

		printf("\n\n\n\n\t\t\t Replacement successfully..!");
		Sleep(1500);
		break;
	}
}

void printFile(FILE *fptr1)
{
    rewind(fptr1);

    char data[MAX];

    printf("\n\n");
    for(int line = 0; fgets(data, MAX, fptr1) != NULL;)
    {
        printf(" %i.  %s\n", ++line, data);
    }
}

void hideCursor()
{
    HANDLE cursorHandle = GetStdHandle(STD_OUTPUT_HANDLE);
    CONSOLE_CURSOR_INFO info;
    info.dwSize = 100;
    info.bVisible = FALSE;
    SetConsoleCursorInfo(cursorHandle, &info);
}


The line is replaced but not like I expected, the file.txt has this content:


Andrea Michele Rome Italy 3475896523
Anna Stroica Moscow Russia 0562314587
Gigi Becali Bucharest Romania 0758963258


..and if I replace line 2 with the following line George Kali Oslo Norway 03265897452

I get something like this:


George Kali Oslo Norway 03265897452
Andrea Michele Rome Italy 3475896523

Gigi Becali Bucharest Romania 0758963258


What I have tried:

I deleted these lines from line 157:

C++
printf("\n\n\n\tName:       ");
scanf("%49s", info.name);
printf("\n\n\tLast name:  ");
scanf("%49s", info.lastname);
printf("\n\n\tCity:       ");
scanf("%49s", info.city);
printf("\n\n\tCountry:    ");
scanf("%49s", info.country);
printf("\n\n\tPhone:      ");
scanf("%19s", info.tel);

fprintf(fptr2, "%s %s %s %s %s\n", info.name, info.lastname, info.city, info.country, info.tel);


It takes input with fgets(data2, MAX, stdin); and I have to write all data within 1 single line and space between the words and it works.. but this is not what I want..

How can make it work with the first code .. I mean without deleting the piece of code?
Posted
Updated 5-Oct-20 22:05pm
v3

I would try printing your strings with single quotes around them so you can see if you have extra newlines in some strings. You can do that by using '%s' as your format specifier. IF that is the case then you need to make sure you remove them from your input. When I read data I almost always strip off newlines first because I find it simplifies a lot of things.
 
Share this answer
 
Comments
M@gelearn 5-Oct-20 19:18pm    
Well I add this:

int len = strlen(data2);
if(data2[len - 1] == '\n')
data2[len - 1] = '\0';

after the:

fgets(data2, MAX, stdin);

and I clean the new line. Now I get all lines included the line I wanted to change without any new line between them.. still the problem persist, comming back to my first question, that the line 2 must be deleted and the new line must take THAT place, instead my line take the first place everytime.
Rick York 5-Oct-20 21:30pm    
I recommend learning how to use a debugger. It should show you where the problem happens if you step through your code. They are an indispensable tool.
A better way would be to read all the input records first into an array of Info structures. You can then much more easily find the item to replace, and then write out the updated data.
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900