Reputation: 105
I have a file with data like this
{0 /Data1/ , 0x00, 0, 0xFF},
{1 /data2/ , 0x00, 0, 0xFF},
{2 /data3/ , 0x00, 0, 0xFF},
{3 /data4/ , 0x00, 0, 0xFF}, ...
I want to print only the second column of each line. Below is the code I worked on.
#include<stdio.h>
#include<string.h>
int main ()
{
char filename[] = "file.txt";
FILE *file = fopen(filename, "r");
if(file!= NULL)
{
char line[128];
char * word1;
char word2;
char word3;
int i=0;
clrscr();
while ( fgets( line, sizeof line, file)!= NULL)
{
i=0;
word1 = strtok(line, " ,");
while(word1!= NULL)
{
i++;
if(i==2 ){
printf("%s\n",word1);
}
word1 = strtok(NULL," ,");
}
}
fclose(file);
}
else
{
perror(filename);
}
getch();
return 0;
}
it works fine. Can I save the value Im printing in each line into an array? I tried something like this
if(i==2){
word2 = * (word1);
}
printf("%s\n",word1);
But it give me a null pointer assignment. How to store the values Im printing into an array?
Upvotes: 1
Views: 3223
Reputation: 16724
Try something like this:
#define MAX_BUFFER_SIZE 256
/* ... */
char ** lines = malloc(MAX_BUFFER_SIZE + 1);
char ** p = lines;
char ** newbuf;
int len;
int bytesloaded = 0;
int buf_size = MAX_BUFFER_SIZE;
assert(lines != NULL);
//... loop etc..
if(i==2 ){
len = strlen(word1);
bytesloaded += len;
if(bytesloaded >= buf_size) /* Controls buffer size. For avoid buffer overflow/heap corruption/UB. */
{
buf_size += MAX_BUFFER_SIZE;
newbuf = realloc(lines, buf_size);
if(!newbuf) /* return or break. */
{
printf("Allocation failed.\n");
free(lines);
return 1;
}
lines = newbuf;
}
*p++ = word1; /* store the word in lines */
printf("%s\n",word1);
}
Note: Don't forget to put the 0-terminator,\0
, in array, after end of first loop.
I haven't tested this code,but I believe that it works.
It a simple example how to do: a dynamic memory allocation
,control the size of it,memory re-allocation and values storage.
Upvotes: 0
Reputation: 842
You are saving only the first char of string word1 into word2.
If you want store all 2nd columns you need to alloc a dynamic array of pointers to (char *) and then to each word/column alloc space to the word and copy with a strcpy because word1 is changing on each iteration of while so you can't save only the refence.
Upvotes: 1
Reputation: 473
You could use a dynamically allocated array, which you grow as you need more space. See Why does a large variable length array has a fixed value -1 even if assigned to in C? for more help.
Upvotes: 0