Thread: Problems with Reading and copying string from txt to console

  1. #16
    Registered User
    Join Date
    Dec 2017
    Posts
    836
    There were some errors in the previous (untested) code I posted. In particular some incorrect variable names and extraneous ampersands before the string variables in the fscanf. Anyway, here's something that (barely) works for the format that you posted afterwards.
    Code:
    #include <stdio.h>
    #include <stdlib.h>
    #include <string.h>
     
    int main() {
        char search_id[100];
     
        printf("Enter ID: ");
        scanf("%s", search_id);
          
        FILE *fp = fopen("registration.txt", "r");
        if (!fp) {
            perror("Cannot open input file");
            exit(EXIT_FAILURE);
        }
     
        int cnt = 0;
        char line[1000], id[100], name[100], gender[100], age[100], birthday[100],
             food[100], start_d[100], end_d[100], course[100], fee[100];
     
        while (fgets(line, sizeof line, fp) != NULL)
        {
            if (!line[strspn(line, " \t\n")]) continue;  // blank or only whitespace
     
            if (sscanf(line, " ID:%99s", id) != 1) break;
            if (fscanf(fp, " Name:%99s Gender:%99s Age:%99s Birthday:%99s"
                           " Food:%99s Start date:%99s End date:%99s ",
                       name, gender, age, birthday, food, start_d, end_d) != 7) break;
     
            // course can contain spaces
            if (fgets(line, sizeof line, fp) == NULL) break;
            char *p = strchr(line, ':');
            if (!p) break;
            strcpy(course, p + strspn(p, ": \t\n")); // skip space, copy to course
            p = strchr(course, '\n'); // remove newline ...
            if (p) *p = '\0';         // ... if present
     
            if (fscanf(fp, " Fee:%99s", fee) != 1) break;
     
            if (strcmp(id, search_id) == 0)
            {
                printf("\n%s\n%s\n%s\n%s\n%s\n%s\n%s\n%s\n%s\n%s\n",
                       id, name, gender, age, birthday, food,
                       start_d, end_d, course, fee);
                ++cnt;
            }
        }
     
        fclose(fp);
      
        if (cnt == 0)
            printf("\nError: id %s not found.\n", search_id);
        else
            printf("\nFound %d record%s for id %s.\n",
                   cnt, cnt > 1 ? "s" : "", search_id);
     
        return 0;
    }
    The world hangs on a thin thread, and that is the psyche of man. - Carl Jung

  2. #17
    null pointer Structure's Avatar
    Join Date
    May 2019
    Posts
    240

    Post

    GOAL:
    the goal is to try and read a txt file and print the content in the console
    searching the id, it should display the the information for that specific id on the console

    SOLUTION:
    Code:
    #include <stdio.h>
    #include <string.h>
    
    char chosen_ID[100], line_data[1024], record[2048];
    
    void rem(char * s, char *what) {
        char *p = s; int l = strlen(p);
        while(p[l-1] == what[0]) p[--l] = 0;
        while(*p && (*p == what[0])) ++p, --l;
        memmove(s,p,l+1);
    };
    
    int readRecord(char *record_data,char *selector) {
        int read_record = 0;
        int skipper = 0;
        char *token = strtok(record_data, ":"); 
        while (token != NULL) {
            if (read_record == 1) {
                rem(token,":");
                if (sizeof(token)>1) printf("%s: ", token);
            };
            if (strcmp(token,selector) == 0) {
                read_record = 1;
            };
            token = strtok(NULL, ":"); 
            if ((skipper % 2) && (read_record == 1)) {
                printf("\n");
            };
            skipper++; 
        };
        return read_record;
    };
    
    void sweep(char *filename,char *getID) {
        FILE *fp = fopen(filename, "r");
        while(fgets(line_data, sizeof(line_data), fp) != NULL) {
            if ( (strcmp(line_data,"-\n") == 0) || (strcmp(line_data,"-") == 0) ) {
                int result = readRecord(record,getID);
                if (result == 1) break;
                memset(record,0,sizeof(record));
            } else {
                if (strcmp(line_data,"|\n") != 0) {
                    rem(line_data,"\n");
                    strcat(line_data,":");
                    strcat(record,line_data);
                };
            };
        };
        fclose(fp);
    };
    
    int main(int args,char *argv[]) {
        printf("ID:"); 
        scanf("%s\0",chosen_ID);
        sweep("data.txt", chosen_ID);
        return 0;
    };
    quick n dirty
    Last edited by Structure; 01-08-2020 at 06:09 PM.
    "without goto we would be wtf'd"

  3. #18
    Registered User
    Join Date
    Dec 2017
    Posts
    836
    @Joe1709, beware of people like "Structure" who not only don't know C very well, but don't even know how to properly use a compiler. His "code" is riddled with errors. Just ignore him. Everyone else does.
    The world hangs on a thin thread, and that is the psyche of man. - Carl Jung

  4. #19
    null pointer Structure's Avatar
    Join Date
    May 2019
    Posts
    240

    Thumbs down whatever dude

    Quote Originally Posted by john.c View Post
    @Joe1709, His "code" is riddled with errors.
    pffffft...

    beware of people like "Structure"

    what in tf ? lmao

    fyi: i would suggest defining 100 since you used it a million times. also your brackets blow.

    and since your rude... this is awful:
    sizeof line
    have you ever used a function before ?
    Last edited by Structure; 01-08-2020 at 06:28 PM.
    "without goto we would be wtf'd"

  5. #20
    misoturbutc Hodor's Avatar
    Join Date
    Nov 2013
    Posts
    1,738
    Quote Originally Posted by Structure View Post
    pffffft...

    have you ever used a function before ?
    What's wrong with sizeof line? That's exactly how I'd write it. sizeof is an operator, not a function

  6. #21
    null pointer Structure's Avatar
    Join Date
    May 2019
    Posts
    240
    sizeof is an operator, not a function


    lol, i stand corrected.

    POINT:
    don't even know how to properly use a compiler.

    "without goto we would be wtf'd"

  7. #22
    misoturbutc Hodor's Avatar
    Join Date
    Nov 2013
    Posts
    1,738
    Quote Originally Posted by Structure View Post


    lol, i stand corrected.

    POINT:



    I don't think any of this is useful to the OP, but for what it's worth I often write code snippets on here that bear little resemblance to how I write C in real life. The main reason is that if someone is asking about parsing a simple file or asking about linked lists or some other first semester topic it's quite likely that they're new to programming. I try and think back to when I was at the same stage and attempt to imagine what I'd understand or what my teachers would have wanted. I don't intentionally write code that's wrong, but I often write code on here in a way that I'd not normally approach things. I'm not going to take sides but I think that john.c's approach is more "obvious" than yours and more likely closer to what the OP's teacher expects. Is your code better? I don't know and it doesn't really matter. Besides, I haven't looked at your code or john.c's code in any great detail. I've compiled yours though and it doesn't compile without warnings so that's a bit of a red flag :P

  8. #23
    misoturbutc Hodor's Avatar
    Join Date
    Nov 2013
    Posts
    1,738
    Quote Originally Posted by Joe1709 View Post
    Joe was born on the 15th day of the 15th month? :-o

  9. #24
    C++ Witch laserlight's Avatar
    Join Date
    Oct 2003
    Location
    Singapore
    Posts
    27,509
    Quote Originally Posted by john.c
    The code you've posted wouldn't even compile if it was part of a complete program (e.g., line 25).
    Unfortunately, line 25 is insidiously syntactically correct. The code could be "correctly" formatted as:
    Code:
    if (same == 0)
    {
        /* ... */
    }
    else
        (diff == 0);
    
    {
        printf("ERROR\n");
    }
    Quote Originally Posted by Structure
    same should be either 1 or 0, true or false
    It's just poor naming: same holds the return value of strcmp, which isn't boolean, but rather one of three possible values (or ranges thereof) to be compared with 0. It is more common to directly compare the return value of strcmp with 0 than to store it in a variable since if you do want to store something, it would be the result of the comparison, which means the result of comparing with 0.

    Quote Originally Posted by Structure
    Code:
    if (sizeof(token)>1) printf("%s: ", token);
    You probably meant to call strlen instead of using sizeof here, and perhaps use >= or compare to 0.
    Quote Originally Posted by Bjarne Stroustrup (2000-10-14)
    I get maybe two dozen requests for help with some sort of programming or design problem every day. Most have more sense than to send me hundreds of lines of code. If they do, I ask them to find the smallest example that exhibits the problem and send me that. Mostly, they then find the error themselves. "Finding the smallest program that demonstrates the error" is a powerful debugging tool.
    Look up a C++ Reference and learn How To Ask Questions The Smart Way

  10. #25
    misoturbutc Hodor's Avatar
    Join Date
    Nov 2013
    Posts
    1,738
    Quote Originally Posted by Structure View Post


    lol, i stand corrected.

    POINT:



    Well, I've compiled both now. john.c's code works, yours doesn't. So I guess that settles things

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. problems copying C-code into folder
    By kiwifreak3 in forum Windows Programming
    Replies: 1
    Last Post: 05-12-2012, 10:37 AM
  2. Problems with copying strings
    By Veneficvs in forum C++ Programming
    Replies: 7
    Last Post: 04-27-2010, 07:40 AM
  3. Have problems with copying my array!
    By AvaGodess in forum C Programming
    Replies: 11
    Last Post: 09-25-2008, 12:56 AM
  4. Replies: 1
    Last Post: 10-31-2005, 11:36 AM
  5. String Copying problems.
    By Red Army in forum C++ Programming
    Replies: 4
    Last Post: 06-04-2002, 05:16 PM

Tags for this Thread