Nova Stark
Nova Stark

Reputation: 55

Selectively reading string part of a file using C

I have a .txt file with strings each line and a number assigned to each string and a - in between the string and the number.

String file

Now I want to read only the string part not the number or the - in between, store them in an array and write only the strings in another file.

I used the following approach:

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

#define MAX 100

struct String {
    long long int num;
    char name[50];
    char C;
} S[MAX], temp;

void file_write(int n, struct String S[]) {
    FILE *pp;
    pp = fopen("std3.txt", "a");       //second file where I want to write only string part.
    for (int i = 0; i < n; i++) {
        fprintf(pp, "%s", S[i].name);    //storing the strings in another file
        fputs("\n", pp);
    }
    fclose(pp);
}

int main() {
    int n;
    FILE *fp;
    fp = fopen("str.txt", "r");
    printf("Enter the number of strings : ");
    scanf("%d", &n);
    for (int i = 0; i < n; i++) {
        fscanf(fp, " %[^\n]", S[i].name);
        fscanf(fp, "%lld", &S[i].num);
        fscanf(fp, "%c", &S[i].C);
    }
    file_write(n, S);
    fclose(fp);
    return 0;
}

But I'm getting an undesirable output:

enter image description here

Upvotes: 1

Views: 430

Answers (2)

vmp
vmp

Reputation: 2420

Scanf (and its variations) is a very powerful function... I think the following line is what you want.

for(int i=0;i<n;i++)
{
    fscanf(fp, "%*[^A-Z]%[^\n]", S[i].name);
}

A brief description of what it does is: It discards any character that is not a capital letter then reads everything from the first capital letter until the end of line.

If the names are allowed to start with lowercase, you can change it to:

 fscanf(fp, "%*[^A-Za-z]%[^\n]", S[i].name);

Upvotes: 0

chqrlie
chqrlie

Reputation: 144685

Here is a simple solution using fscanf() and the * assignment suppression option:

#include <stdio.h>

int main() {
    int n = 0;
    FILE *fp = fopen("str.txt", "r");
    // second file where I want to write only string part.
    FILE *pp = fopen("std3.txt", "a");
    if (fp == NULL || pp == NULL) {
        fprintf(stderr, "cannot open files\n");
        return 1;
    }
    printf("Enter the number of strings: ");
    scanf("%d", &n);

    for (int i = 0; i < n; i++) {
        char name[50];
        int c;
        if (fscanf(fp, "%*d - %49[^\n]", name) == 1) {
            fprintf(pp, "%s\n", name);
            /* flush any extra characters and the newline if present */
            while ((c = getc(fp)) != EOF && c != '\n')
                continue;
        } else {
            break;
        }
    }
    fclose(fp);
    fclose(pp);
    return 0;
}

Upvotes: 1

Related Questions