gozlemci |
03-06-2010 01:42 AM |
Error during reading a file line by line in C
Hi there;
I have a code over there. It reads a line from file and converts contents of it to double.
Code:
/*
* fileRead.c
*
* Created on: Mar 4, 2010
* Author: asimavi
*/
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#include <string.h>
#define CONS_MAX_DIMENSION_X 500
#define CONS_MAX_DIMENSION_Y 500
#define CONS_NULL_VALE -9
#define SAMPLE_FILE "deneme.txt"
//Matrix file element
typedef struct matrix
{
int height;
int width;
double data[CONS_MAX_DIMENSION_Y][CONS_MAX_DIMENSION_X];
}MATRIX;
//Client File element
typedef struct client
{
int coreNumber;
MATRIX* matrixFirst;
MATRIX* matrixSecond;
}CLIENT;
MATRIX Matrix_Buffer [20];
MATRIX Result_Buffer [20];
//Function definitions
void convertToDouble(char *searchBuffer, int yCoordinates,int matrixNumber);
void initialize(char* startBuffer);
void copyString(char *tobeCopied, char *source,int startIndex,int lenght);
int main( int argc, char* argv[] ) {
FILE *fp;
int i=0;
char searchBuffer[100];
//Check the avalibility of the program
if((fp=fopen(SAMPLE_FILE,"r")) == NULL) {
printf("Cannot open file.\n");
return(-1);
}
while(fgets(searchBuffer , 80 , fp) != NULL)
{
printf("okunan veri:%s - ",searchBuffer);
//convert one line to matrix here.
convertToDouble(searchBuffer,i,0);
i++;
}
return 0;
}
void convertToDouble(char *searchBuffer,int yCoordinates,int matrixNumber)
{
char *ptr = (char *)malloc(100 * sizeof (char));
char *ptr2;
int start=0;
int common=0;
double temp;
int termCounter=0;
while(1)
{
if(searchBuffer[common] == ',' || searchBuffer[common] == '\0')
{
//Another double
copyString(ptr,searchBuffer,start,common-start);
// ptr = strncpy( ptr2, &searchBuffer[start], common-start );
start = common+1;
temp = atof(ptr);
Matrix_Buffer[matrixNumber].data[yCoordinates][termCounter] = temp;
termCounter++;
if(searchBuffer[common] == '\0')
{
break;
}
}
common++;
}
initialize(searchBuffer);
}
void copyString(char *tobeCopied, char *source,int startIndex,int lenght)
{
int i=0;
while(i<lenght)
{
tobeCopied[i++] = source[startIndex++];
}
}
void initialize(char* startBuffer)
{
int i=0;
while(i<99)
{
startBuffer[i] = '\0';
}
}
Assume that below is the input:
44.0 , 67.0 , 15.0 , 65.0
14.0 , 88.0 , 122.0 , 11.0
65.0 , 72.0 , 132.0 , 56.0
57.0 , 62.0 , 22.0 , 176.0
This program only reads the first line of the input file and terminates. It must read whole file, how can I solve that?
I'm using Eclipse IDE for C/C++ Developers and ubuntu as operation system.
Thanks in advance!
|