How to compare the first string from last line in a file.txt 'C'

Pages: 12

I need to compare the first string from the last line in a file.txt

So if the file.txt contains the following:

22310 01 09 2020
22500 01 10 2020
22700 01 11 2020


How to compare my string with 22700 ? which is the first string, last line in my file.txt
Last edited on
Here is how you get the first number in the last line:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
#include <iostream>
#include <fstream>

int main () {
    std::ifstream myfile ("file.txt");
    if (myfile.is_open())
    {
        int number{0}, dummy{0}; // MAKE THEM string's IF YOU LIKE BUT WHY??
        while(myfile >> number >> dummy >> dummy >> dummy)
        {
            // NOTHING NEEDS TO BE DONE HERE
        }
        std::cout << number << '\n'; // <-- THE FIRST/LAST NUMBER
        
        myfile.close();
    }
    else
        std::cout << "Unable to open file";
    return 0;
}
Ohh thanks againtry I'll see how can I write your code in C (I did mention 'C' in the question), and
int number{0}, dummy{0}; // MAKE THEM string's IF YOU LIKE BUT WHY??
because 22700 when I save them on the file.txt was a char str[MAX]; and I thought I have to retrieve it as a string, but what I really need to do is not the compare, as I mention in my question I only have to do a subtraction from the current input and the last number in the list as it is the first number 22700. So I wrote a function like this:

1
2
3
4
5
6
7
8
9
10
11
12
int diferentaIndex(char index1[MAX], char index2[MAX])
{
    long int rezultat;
    long int x, y;

    x = atoi(index1);
    y = atoi(index2);

    rezultat = y - x;

    return rezultat;
}


and past this in my other function because the input from the user is a char not an int.
Last edited on
To obtain the first part of the last line as a string:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
#include <fstream>
#include <iostream>
#include <string>

int main()
{
	std::ifstream ifs("file.txt");

	if (!ifs.is_open()) {
		std::cout << "Cannot open file\n";
		return 1;
	}

	std::string last;

	for (std::string dum; ifs >> last >> dum >> dum >> dum; );

	std::cout << "last is " << last << "\n";
}

And after the subtraction was made ..I need to print it on the file as the result. like this :


22310 01 09 2020 0
22500 01 10 2020 190
22700 01 11 2020 200
Last edited on
Hello seeplus ,.. well I guess no one see I specify 'C' on the question.. but yes seems like your code is similar to againtry so I believe that is correct. I ques I have to find out how to write it on 'C'.
I'll see how can I write your code in C


Sorry. Didn't read the title properly.

For c to get the last id as a char array:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
#include <stdio.h>
#include <stdlib.h>

int main()
{
	FILE* inpf = fopen("file.txt", "r");

	if (inpf == NULL) {
		puts("Cannot open input file");
		return 1;
	}

	char id[6] = {0};

	for (int dum = 0; fscanf(inpf, "%5s %d %d %d", id, &dum, &dum, &dum) != EOF; );

	printf("Last is %s\n", id);
}


and to get it as a number:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
include <stdio.h>
#include <stdlib.h>

int main()
{
	FILE* inpf = fopen("file.txt", "r");

	if (inpf == NULL) {
		puts("Cannot open input file");
		return 1;
	}

	int id = 0;

	for (int dum = 0; fscanf(inpf, "%d %d %d %d", &id, &dum, &dum, &dum) != EOF; );

	printf("Last is %d\n", id);
}

Last edited on
:D .. Ahh, thank you seeplus.. I really need to learn something about C++, Hahah I don't really understand this notation
std::ifstream
I mean I know what does it mean (standard file stream which is the equivalent of FILE* inpf = fopen("file.txt", "r");"), but those :: just scare me, and they are pretty used in C++.
Last edited on
In c++, std:: just means that what follows is defined in the std namespace - as opposed to the global namespace.

If you're doing small simple C++ programs, you can put using namespace std; after the #includes and then std:: isn't needed.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
#include <fstream>
#include <iostream>
#include <string>
using namespace std;

int main()
{
	ifstream ifs("file.txt");

	if (!ifs.is_open()) {
		cout << "Cannot open file\n";
		return 1;
	}

	string last;

	for (string dum; ifs >> last >> dum >> dum >> dum; );

	cout << "last is " << last << "\n";
}

Last edited on
One benefit of using C++ in this context is that you can use the C++ string container rather than c-style char arrays. With C++ string, you don't need to bother about the size of the string as this is handled automatically.
Ohh now make sens... :) But even if that's more simple, why do I see in most cases programers that prefer to not define using namespace std; and to use std: in code, I mean .. isn't that more complicated to add that every time you write a line, which has to include std:: ???
Last edited on
Consider. C++ has a string container. Say you want to use another library that also has a string container. If both are called string, which does the compiler know to use? This is where namespaces come in. Stuff that comes with C++ is in the std:: namespace, other libraries have their own namespace names. By specifying the required namespace name when using a container etc the compiler knows which one to use. If no other libraries are used, then there's no problem with using namespace std; The problem comes when using other/multiple libraries. Then you can/will get into problems if you have using namespace std;. That is why most professional programmers don't use this but specify std:: every time when needed. Even if you have using namespace std; in your .cpp code, don't put it into a .h (header) file.
Last edited on
@!@.. Ohh I got it now, that explains everything ... So I guess I have to thank you even for the lesson for today .. ;)
I'm sorry seeplus I modify back the
Mark as solved
, I put your code in practice but I don't get the first string of the last line in the file, instead I get 0.

I don't know if it's my fault but instead of using printf("Last is %s\n", id);,

I use that in my function :

1
2
3
4
5
6
7
8
9
10
11
12
int diferentaIndex(char index1[MAX], char index2[MAX])
{
    long int rezultat;
    long int x, y;

    x = atoi(index1);
    y = atoi(index2);

    rezultat = y - x;

    return rezultat;
}


..and after I used
fprintf()
function to print the result on the file.

I have a char tmp[MAX]; where MAX is 1000 and this is where user input the number which in the int diferentaIndex function should be the char index2[MAX], and the char index1[MAX] should be the the last id as a char array from your function below, but the char index1[MAX] is every time 0. So y - x will be always char index2[MAX] value.

What could be wrong.. or maybe what I AM doing wrong ? Please help.. :\
Last edited on
Note that the above code suggestions work by reading all the file until the last line. If the file is large, this could take several seconds. If performance is an issue, then there is a quicker - but more complicated method - by first seeking to the end of the file and working backwards.
Okay .. I'll provide a bit the code so maybe as I described isn't clear enough:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
struct INFO
{
    char apa[MAX];
    char gaz[MAX];
    char curent[MAX];
    long int diferenta;
};
// TIMP
struct TIMP
{
    char zi[MAX];
    char luna[MAX];
    char an[MAX];
};

int diferentaIndex(char index1[MAX], char index2[MAX])
{
    long int rezultat;
    long int x, y;

    x = atoi(index1);
    y = atoi(index2);

    rezultat = y - x;

    return rezultat;
}
//------------------------------------------------//
// ** Adauga info apa ** //
void adaugaInfoApa(struct INFO* info, struct TIMP* timp)
{
    BOOL found = FALSE;
    FILE *file;
    char fname[MAX] = "apa.c";
    char temp[MAX];
    file = fopen(fname, "a+");

    system("cls");
    printf("\n\t\t\t\tCENTRU INDEX\n\t\t\t\t------------");
    printf("\n\n\n\tSectiunea Adauga Info apa\n\t-------------------------\n\n");
    printf("\n\n   Introduceti Metri cubi:  ");
    scanf("%30s", temp);

    fseek(file, 0, SEEK_END);
    long size = ftell(file);

    do
    {
        rewind(file);
        while(fscanf(file, "%15s", info->apa) == 1)
        {
            if(strcmp(temp, info->apa) == 0)
            {
                found = TRUE;
                printf("\n\n   Indexul introdus exista deja");
                Sleep(1500);
                system("cls");
                fclose(file);
                return;
            }
        }
        if(!found)
        {
            //rewind(file);
            printf("\n\n\n\tData\n\t----");
            printf("\n\n   Ziua:  ");
            scanf("%30s", timp->zi);
            printf("\n\n   Luna:  ");
            scanf("%30s", timp->luna);
            printf("\n\n   Anul:  ");
            scanf("%30s", timp->an);

            if(size != 0)
            {
                char tmpApa[6] = {0};

                for (int ln = 0; fscanf(file, "%5s    |   %d   |   %d   | %d |  %d", tmpApa, &ln, &ln, &ln, &ln) != EOF; );

                info->diferenta = diferentaIndex(tmpApa, temp);

                fprintf(file, "%s    |   %s   |   %s   | %s |  %ld \n", temp, timp->zi, timp->luna, timp->an, info->diferenta);
            }
            else
            {
                fprintf(file, "%s    |   %s   |   %s   | %s |  0 \n", temp, timp->zi, timp->luna, timp->an);
            }


            fclose(file);

            system("attrib +h +s apa.c");

            printf("\n\n\n\tIndexul a fost salvat in baza de date");
            Sleep(2000);
            system("cls");
            return;
        }
    }while(size != 0);
}
Last edited on
At line 79 I used the int diferenta from the struct INFO = with my function int diferentaIndex(char index1[MAX], char index2[MAX])

And it should be int diferentaIndex(char tmpApa[MAX], char temp[MAX])

so finaly temp - tmpApa then printing it on the same file at the end of every line.
Last edited on
SO the result in the file will look like this:


-------------------------------------------------
| Nr. | M.C. | Zi | Luna | An | Dif.|
| 1. | 11800 | 01 | 09 | 2020| 0 |
| 2. | 12000 | 01 | 10 | 2020|200| <- Here I make the difference between
........................................................................11800 and 12000.
...
....
|------------------------------------------------ |
Last edited on
 
for (int ln = 0; fscanf(file, "%5s    |   %d   |   %d   | %d |  %d", tmpApa, &ln, &ln, &ln, &ln) != EOF; );


That doesn't match the format of the file given earlier.

What is the format/example of the file you are actually using?

I didn't write in my question the format I'm using... but, Yes indeed that is the format I'm using I only add a last %d for the difference info->diferenta.

I just copy your earlier code:

 
for (int dum = 0; fscanf(inpf, "%5s %d %d %d", id, &dum, &dum, &dum) != EOF; );


I just only add an extra &dum and this
|
between them, but is exactly same you wrote.
Pages: 12