printing the checksum of a txt file without printing the file path

279 views Asked by At

I want to compute the checksum of a txt file using C in mac, thus I wrote a simple program as

#include <iostream>
#include <stdio.h>
using namespace std;

int main() {
    FILE *in;
    char buff[512];
    if(!(in = popen("shasum ritesh_file_test.txt", "r")))
    {
        return 1;
    }
    while(fgets(buff, sizeof(buff), in)!=NULL)
    {
        cout << buff;
    }

    printf ("checksum = %s",buff);
    pclose(in);
    return 0;

it prints the checksum of txt file , but also it prints the path of file. as

30b574b4ddbc681d9e5e6492ae82b32a7923e02e ritesh_file_test.txt

How do I get rid of this path and only access the checksum value?

2

There are 2 answers

0
Sourav Ghosh On

The output format of shasum is of form

 <HASH> <Filename>

so, the hash value and the file name are separated by a space. One possible way, to separate the hash from the complete outpuy, is to tokenize buff before printing.

You can make use of strtok() and use space () as delimiter to take out only the checksum value.

That said, in C, you don't include #include <iostream>, don't use using namespace std; and don't write cout. Moreover, use a C compiler to compile C code.

0
Ken Y-N On

Three solutions:

  1. Since you are using a shell, shasum ritesh_file_test.txt | awk '{ print $1; }' might work.

  2. Since you are using C++:

    std::string checksum(buff);
    checksum = checksum.substr(0, checksum.find(' ') -1 );
    
  3. Or even, since a hash is always 40 bytes:

    std::string checksum(buff, 40);
    

I leave error checking as an exercise for you!