0
int main(int argc, char *argv)
{
    char filename[20]={};
    int count=0;

    if(argc==2)
    {
        strcpy(filename, argv[1]);
    }
    else
    {
        printf("Need 2 command line parameters\n");
    }

    FILE *fp=fopen(argv[1], "r");

    while(fgets(filename, 20, fp))
    {
        count++;
    }

    fseek(fp, 0, SEEK_SET);

    int ptr=(int)malloc(count*sizeof(int));
    while(fgets(filename, 20, fp))
    {
        ptr[i]=
    }

    return 0;

for example, my numbers in file are 19293 18239 19405 29302 10492 in each line, and I would like to put each line in an array. How do I do this? It doesn't have to be in a while loop.

  • What's the purpose of `strcpy`ing `argv[1]` to `filename`, if you are overwriting it later `while(fgets(filename, 20, fp))`? – Shubham Jul 06 '20 at 01:07
  • `int ptr=(int)malloc(count*sizeof(int));` You can't do this. Here's another error assignment operator used without `rvalue` and line terminator `;` in `ptr[i]=`. – Shubham Jul 06 '20 at 01:08
  • it is meant to overwrite later, while(fgets(filename,20,fp)) is meant for counting how many lines(or numbers) in the file. im using malloc to free space and overwrite another file. Please ignore while loop after the malloc function. I did it wrong, still trying to figure it out. –  Jul 06 '20 at 01:38
  • are u sure that you are allocating memory `int ptr=(int)malloc(count*sizeof(int));` in the right way. – Shubham Jul 06 '20 at 02:00
  • You want to put all the contents of your file inside an array, isn't it? – Shubham Jul 06 '20 at 02:02

2 Answers2

1

I think your question is that you want to store the content you read as a string each line.Ok, there are serveal methods to realize it. If you don't care the effenciency, you can define a char pointer array as max as possible to contain all lines in your files. And you can do like this:

char* content[MAX_LINE] = { NULL };
char tmp[20];
char* ptr;
int i=0;
size_t ret;
FILE* fp;
fopen_s(&fp,"1.txt", "r");
while (fgets(tmp, 20, fp) != NULL)
{
    ret = strlen(tmp);
    ptr = (char*)malloc(ret+1);
    strcpy_s(ptr, ret+1, tmp);
    content[i++] = ptr;
}

And the better way is using pointer list.

vincent
  • 81
  • 6
  • if the number is smaller than 0x7fffffff, you can do it with atoi, otherwise, consider atol or atoll etc. – vincent Jul 06 '20 at 01:56
  • Read [why-while(!feof(file))-is-always-wrong?](https://stackoverflow.com/questions/5431941/why-is-while-feof-file-always-wrong). – Shubham Jul 06 '20 at 02:12
0

If you want to read and store the whole content of your file in an array, you can do this in this simple way, though there are also other ways:

while( ( c = getc(file) ) != EOF )
  buffer[i++] = c;

where buffer is an char array of 1000 elements(it could be any number, you want), c is a char, and i is an int initialized with 0.

Shubham
  • 1,153
  • 8
  • 20