Hello. I was searching on how to copy the string from the first point in the file to the index of comma -1. I have a .mrk file that i would be reading. My idea is that the loop will go through the file and find the comma. There will be a counter to check the num of characters. When found, the first char to char at index of comma-1 is copied to a seperate array. But i do not know how to implement this. This is my code:

FILE *check = fopen("check.mrk","r");

   if (check == 0)
   {
    printf("Could not open the file.\n");
   }
   else
   {
      int i;

      while((i=fgetc(check))!=EOF)
      {
         printf("%c",i);
         if (i == '\n')
         {
            printf("\n");
        }
      }
      fclose(check);
   }

A guidance on this would be appreciated. Thank you.

Dani AI

Generated

A few practical tips and a compact, safer pattern you can reuse. got this working with strtok, and the community correctly pointed out the core ideas (scan for the comma, isolate the text, store it). Common pitfalls in the thread were copying fixed 80-byte chunks (which can pull in uninitialized bytes or truncation) and printing raw buffer without a format specifier (as warned). Below is a concise approach that reads each line of arbitrary length, finds the first comma, copies only the characters before it into a newly allocated string, and stores those strings in a dynamically growing array.

/* POSIX example: getline + strcspn + realloc */
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

int main(void) {
    FILE *f = fopen("check.mrk", "r");
    if (!f) return 1;
    char *line = NULL;
    size_t llen = 0;
    ssize_t n;
    char **items = NULL;
    size_t count = 0, cap = 0;

    while ((n = getline(&line, &llen, f)) != -1) {
        while (n > 0 && (line[n-1] == '\n' || line[n-1] == '\r')) line[--n] = '\0';
        size_t pos = strcspn(line, ",");
        char *field = malloc(pos + 1);
        if (!field) break;
        memcpy(field, line, pos);
        field[pos] = '\0';
        if (count == cap) {
            cap = cap ? cap * 2 : 8;
            char **tmp = realloc(items, cap * sizeof *items);
            if (!tmp) { free(field); break; }
            items = tmp;
        }
        items[count++] = field;
    }

    free(line);
    fclose(f);
    for (size_t i = 0; i < count; ++i) { puts(items[i]); free(items[i]); }
    free(items);
    return 0;
}

Notes and caveats: getline is POSIX; on non-POSIX systems replace it with a safe growable reader or use repeated fgets with careful tracking of bytes read. strtok (which you used) mutates the buffer and is not reentrant; use strtok_r or manual slicing (as above) if you need to keep the original text or parse concurrently. If your data can contain quoted fields with embedded commas (true CSV), use a proper CSV parser rather than simple comma-splitting. Always check malloc/realloc returns, free allocated memory, and handle lines that contain no comma (above code treats the whole line as the field).

Recommended Answers

All 7 Replies

copy the string from the first point in the file to the index of comma -1

Copy to where? Another file? A memory buffer in the program? Display on the console?

If it's a memory buffer in the program, you'll need to allocate storage with malloc or something else. For the other two, you don't. Hence the approach might be different. Lines 14 to 17 seem counterproductive. Seems like you are going to be printing newlines twice? Seems like they should be deleted.

I don't see anywhere where you're checking for a comma. Seems like you should perhaps change 13 to 17 to this?

if(i == ',')
{
    break;
}
printf("%c", i);

Thanks for your reply. My main problem is to copy contents from file and assign it an array. I have tried to implement fgetc but my program allows the user to accept new person with their details. So the program is not limitted to a specific size. After i copy the contents of the file to a array, i will tokenize the array by using the comma present in the file as the delimitter and assign the tokenized content to a specific variable like person_name. This is my new code:

    FILE *check = fopen("check.mrk","r");   
    int i=0,j=0;
    char line[8000];
    char buffer[81];

    if (check == 0)
    {
        printf("Could not open the file.\n");
    }
    else
    {
        while (fgets(buffer, 80, check) != NULL)
        {
            printf(buffer);
            for (j = 0; j < 80; j++) {
                line[i++] = buffer[j];
            }
        }
        printf("Content of Array.\n");
        printf("%s, \n", line); 
        fclose(check);
    }

I attempted more ways than this but am lost on how to implement them again as i commented them all. For this, it is printing only the first line of the file. The next line would have a comma. thats all. For now, i just want to copy contents of file to array.

  char * pch;
  pch=strchr(str,',');
  while (pch!=NULL)
  {
    pch=strchr(pch+1,',');
  }

this is an example, of one way how you achieve your goal,
it will find the locations of , for you,

however you need to get the location of those , and use a function called strcpy to get the string needed,
however, how confortable are you with pointer??

if not so great then, this might confuse you.

For this, it is printing only the first line of the file.

I'm wondering if perhaps the problem is that you are reading in a line that is LESS THAN 80 characters, then copying 80 characters into line. If the line is 40 characters, then buffer[40] to buffer[79] might contain anything, including the NULL terminator 0, in which case, that's the end of your strange. You don't want to copy uninitialized characters into line and it looks like you're doing that in lines 15 and 16.

Try replacing lines 15 and 16 with the following.

strcat(line, buffer);

Stick the following before line12 to initialize line to an empty string.

line[0] = 0;

This doesn't touch the comma part of your problem, but I think you'll at least get the output you're expecting (the whole file).

oh use the function Strtok(str, ",");instead of strchr(str,',');

char * pch;
  pch=strtok(str,",");
  while (pch!=NULL)
  {
    printf("Keyword found: %s", pch);
    pch=strchr(null,",");
  }

pch will have a string of every keyword

dont use printf(buffer); to debug

memset(buffer,0,sizeof(buffer);
//fill it with data
for (i=0;i<sizeof(buffer);i++)//print every element
{
    printf("[%c]",buffer[i]);//or printf("[%d]",buffer[i]);
}

I have used strtok() to get each strings in the file using while and fgets function and assigning to different initialised arrays using comma as delimitter. It works. Thanks for your replies.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.