Hello All,

I have very basic knowledge of C and I'm trying to write a program to read a single line from an ASCII data file which has following format

" 1337936.4550 6070317.1261 1427876.7852 APPROX POSITION XYZ"

The problem is the position of line is not fixed. Its different in different files. I know the code is not correct, but this is what I could write

#include <stdio.h>
#include <stdlib.h>
#include <string.h>



int main(void)
{
char name, string[20], *chek = "APPROX"; 
float x, y, z; 

printf("\nEnter file name:\t");
scanf("%s", &name);

FILE *file;
file = fopen(name, "r");

while (string!=chek)
{
fscanf(file, "%0.4f %0.4f %0.4f %s", &x, &y, &z, &string);
if(string==chek)
{
printf("\n%f %f %f %s\t", x, y, z, string);
}
else printf("\nLife Sux");
}
fclose(file);

}

Now when I compile it in Unix I get
1readtest.c: In function `main':
1readtest.c:17: warning: passing arg 1 of `fopen' makes pointer from integer without a cast
If I run it anyway, I get "Segmentation Fault"

Please help me. I'm very much frustrated and don't want to end up quitting C.

Recommended Answers

All 5 Replies

name is just a single character. What you want is a character array. char name[255];

Thanx for pointing out that name shoud be an array. But how do I go about locating the line in the file?

I need to print the three float values only.

Please help!!!

scanf("%s", &name);

scanf() is not a good choice to read a string. User fgets() instead.

FILE *file;
file = fopen(name, "r");

What happens if the file doesn't exist. Must check that the file can be opened.
exempli gratiā

if( file == NULL ) {
    < handle the error>
}
while (string!=chek)
string==chek

Even when I question the logic of it, strings can't be compare like that.
Take a look at the function strcmp() instead.

I shall take the name of file as input from user and scan the file for the required fields. Have modified the code a bit. PLease check and comment or convey corrections.

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

int main(void)
{
char name[13], string[20], chek[] = "APPROX POSITION XYZ"; 
float x, y, z; 

printf("\nEnter file name:\t");
scanf("%s", &name);

FILE *file;
file = fopen(name, "r");

while(strcmp(string, "APPROX POSITION XYZ") != 0)
{
fscanf(file, "%f %f %f %s", &x, &y, &z, &string);
i++;
}
printf("\n%f %f %f %s\t", x, y, z, string);
fclose(file);
return(0);
}

PLease check and comment or convey corrections.

What for? You have shown to ignore corrections.
I'll tell you what. Take a look at how to post your code correctly and I guarantee you that people will help more readily.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.