I want to read a txt file.
The text file is:
1,3,1,3,1,1
7,4,1,4,2,1
1,5,1,5,1,1
1,6,1,6,1,1
There are 6 numbers in one line. I want to read numbers 2 lines at one time. I want to save the location I read, do another task, and then read it again from the same place (this is a test). I used “ftell” to save the location I read, and then read it again with “fseek”, but the location was wrong. It should actually output 1, 5, 1, 5, 1, 1. But it gets 5, 1, 5, 1, 1. What’s wrong?
FILE *fp;
int lines_read = 0;
int lines_to_read = 2;
long int pos;
int WORD_MAX = 1000;
int WORD_MAX2 = 100;
int* str;
str = (int*)malloc(sizeof(int)*WORD_MAX);
char* str0;
str0 = (char*)malloc(sizeof(char)*WORD_MAX);
char* str1;
str1 = (char*)malloc(sizeof(char)*WORD_MAX);
long int strc;
char* end = NULL;
int*****S;
for(i=0; i<WORD_MAX; i++) str[i] = 0;
for(i=0; i<WORD_MAX; i++) str0[i] ='';
int i = 0;
for(lines_read = 0 ;lines_read < lines_to_read ; lines_read ++){
if(fgets(str0,WORD_MAX2,fp) != NULL){
for(i = 0; i <= 5; i ++){
strc = strtol(str0,&end,10);
str[i] = (int)strc;
if(i != 5){str0 = end + 1;}
}
S[str[i - 4]][str[i - 3]][str[i - 2]][str[i - 1]][str[i]] = str[i - 5];
pos = ftell(fp);
}
else{
break;
}
}
fseek(fp,pos,SEEK_SET);
fgets(str1,WORD_MAX2,fp);
printf("str1; %sn",str1);
user25544620 is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.
3