-1

I'm having a lot of problems doing this task. I have a txt with only one line of words separated by commas. I have to read this and put it in an array. So far i tried using strtok() but it just gives me errors. Here's my code:

#include<stdio.h>
#include<string.h>
#include<stdlib.h>
#include<omp.h>
int main(){
char string[5000],list[200],*token,s=", ";
int i;
FILE *lista;
    lista=fopen("lista.txt","r");
    i=0;
    token=strtok(string,s);
    strcpy(list[i],token);
    while(fscanf(lista,"%s",string)!=EOF){
        token=strtok(NULL,s);
        strcpy(list[i],token);
        i=i+1;
    }
    fclose(lista);
}

It gives me the" expectig char *restrict" error I'm seriously out of ideas. BTW: I'm in Linux

  • 2
    `char s=", "` is not a string: you're missing a `*`. My compiler even tells me so as the first warning. –  Nov 13 '16 at 00:47
  • You can find the solution here - http://stackoverflow.com/questions/26443492/read-comma-separated-values-from-a-text-file-in-c – Wasi Ahmad Nov 13 '16 at 00:49
  • I just tried what you said but it doesn't change anything, same error appears. expected char * restrict but argument is of type char. – user7151467 Nov 13 '16 at 00:52
  • @user7151467 Which line is giving you this error? If it is the `strtok()` call in line 11, then you clearly *haven't* fixed the problem with your declaration of `s`, which should be `*s = ", ";`. If not, then where is it? I don't think there are many people here willing to play a game of 20 questions just to find out what the problem is. – r3mainer Nov 13 '16 at 01:04
  • If you still have the same error, please update the code in your question with your *current* code. Also, check for any compiler warnings happening *before* your error, and fix those first. –  Nov 13 '16 at 01:36

1 Answers1

1

There are many strange things in your code, but i guess, you want something like this:

char string[5000], *list[200], *token;
char * s = ",";
int i;
FILE *lista;
lista = fopen("C:\\File.txt", "r");

int MAX_FILE_SIZE = 1000;
char * buffer = (char*)malloc(sizeof(char)*MAX_FILE_SIZE);
fread(buffer, sizeof(char), MAX_FILE_SIZE, lista);

list[0] = strtok(buffer, s);
for (int i = 1;; i++)
{
    list[i] = strtok(NULL, s);
    if (list[i] == NULL) 
    {
        break;
    }
}

fclose(lista);

What is strange/wrong in your code:

  • You are passing char* string into strtok function, but this variable is uninitialised when passing
  • You have file pointer lista, but you never read from this file
  • You have variable list which is array of 200 chars, but i guess you want to have variable list as a list of strings
  • strtok eats two parameters, const char* inputString and const char* delimiter. So your variable s should be const char *