LinuxQuestions.org
Share your knowledge at the LQ Wiki.
Home Forums Tutorials Articles Register
Go Back   LinuxQuestions.org > Forums > Non-*NIX Forums > Programming
User Name
Password
Programming This forum is for all programming questions.
The question does not have to be directly related to Linux and any language is fair game.

Notices


Reply
  Search this Thread
Old 04-14-2005, 11:45 PM   #1
indian
Member
 
Registered: Aug 2004
Posts: 137

Rep: Reputation: 15
What is wrong with this C code ?


HI,
I am trying to read come numbers from a text file and than convert those numbers to floats.Here is my code,Everything looks fine but still I am not able to understand that why it is giving segmentation fault:-

AFTER DARK HELMET's SUGESTION I HAVE MODIFIDE THE CODE,BUT IT IS STILL GIVING SEGMENTATION FAULT

Hereis the modified code

Code:
#include<stdio.h>
#include<string.h>
#include<stdlib.h>
#include<math.h>

main()
{
    FILE *fs;
    char ch,d;
    char str[20];

    fs=fopen("text","r");
    int i;
    while((ch=fgetc(fs))!=EOF)
    {
        if( (ch!='\t') || (ch!='\n'))
        {
            i=0;
            str[i]=ch;
            while((ch!='\t') || (ch!='\n') || (ch!=EOF))
            {
                ch=fgetc(fs);
                str[i]=ch;
                i++;
            }
            str[i]='\0';
            func(str);
        }
        else
        {
            continue;
        }
    }
}

func(char *str)
{
        float a;
        a=atof(str);
        printf("%f\t",a);
}
I hope the code is clear to all

regards

Last edited by indian; 04-15-2005 at 12:47 AM.
 
Old 04-15-2005, 12:29 AM   #2
Dark_Helmet
Senior Member
 
Registered: Jan 2003
Posts: 2,786

Rep: Reputation: 374Reputation: 374Reputation: 374Reputation: 374
First, I think your if() statement is incorrect. Shouldn't this:
Code:
if(ch!='\t' ||ch!='\n')
be this:
Code:
if( (ch != '\t' ) && ( ch != '\n' ) )
The way you currently have it, you will always enter the loop. If ch equals '\t' then it is definitely not equal to '\n' and vice versa. It will always enter that if block.


Second: this is probably the cause of your segmentation fault. Earlier in your program, you do this:
Code:
while((ch=fgetc(fs))!=EOF)

Then later, you start reading from the file again with:
Code:
while((ch=fgetc(fs))!='\t')

So, why don't you check for EOF in the second while loop? Isn't it possible you could reach the end of the file in the second loop? You need to change the condition of your second while loop to check for '\t' and EOF.
 
Old 04-15-2005, 01:34 AM   #3
Roptaty
LQ Newbie
 
Registered: Apr 2005
Posts: 6

Rep: Reputation: 0
Re: What is wrong with this C code ?

There are several bugs in this code.
Code:
    fs=fopen("text","r");   #1
    int i;
    while((ch=fgetc(fs))!=EOF)
    {
        if( (ch!='\t') || (ch!='\n'))
        {
            i=0;
            str[i]=ch; 
            while((ch!='\t') || (ch!='\n') || (ch!=EOF)) 
            {
                ch=fgetc(fs); #2
                str[i]=ch;
                i++;
            }
            str[i]='\0';
            func(str);
        }
        else
        {
            continue; #3
        }
    }
#1: You dont check if the file was opened successfully.
#2: In the first run, you check the previous character which you have already checked..
n the first run, you will also overwrite the old str[i] value. Since the value of the i variable is the same as before. You fail to check the value of ch here as well.
#3: Not really needed

One tip: Try using a debugger to check for flaws in your code. I've had some d'oh-experiences with my own code.

Last edited by Roptaty; 04-15-2005 at 01:38 AM.
 
Old 04-15-2005, 02:15 AM   #4
Dark_Helmet
Senior Member
 
Registered: Jan 2003
Posts: 2,786

Rep: Reputation: 374Reputation: 374Reputation: 374Reputation: 374
indian:
I see you edited your code and didn't post a reply. There's no way for people to know you've updated it. People don't get email alerts when you edit a post; only when there's a reply.

I have to repeat the first point I made previously: your conditions in the if-statement and while loops are still wrong. You are using the logical OR operator ( || ) when you should be using the logical AND operator ( && ). The following if statement will never evaluate to false:
Code:
if( (ch!='\t') || (ch!='\n'))
Similarly, your inner while loop will never exit:
Code:
while((ch!='\t') || (ch!='\n') || (ch!=EOF))
Change the logical OR's to logical AND's.
 
Old 04-15-2005, 03:49 AM   #5
indian
Member
 
Registered: Aug 2004
Posts: 137

Original Poster
Rep: Reputation: 15
Ya DH...now it is running....there were definately some problem with while loops ..and thanks Roptaty for good suggestions...I shud had used AND isntead of OR .

Thanks again to both of u..
 
Old 04-15-2005, 08:53 AM   #6
max_rsr
LQ Newbie
 
Registered: Mar 2005
Posts: 20

Rep: Reputation: 0
ok here's your complete working code .there were a few redundancies in your code
I have tested the program it should work
this should solve your problem.

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

void func(char str[]);

int main()
{
int i = 0;
char ch;
char str[20];
FILE *fs;

fs = fopen("text","r");
if(!fs) {
printf("\ncannot open input file");
exit(1);
}

while((ch = getc(fs))!=EOF) {
if(ch!= ' '&&ch!= '\t'&&ch!='\n')
str[i] = ch;
i++;
}

str[i] = '\0';

func(str);
}

void func(char str[])
{
float a;

a = atof(str);
printf("\n%f",a);


}


Hope u appreciate it.

Last edited by max_rsr; 04-15-2005 at 09:03 AM.
 
Old 04-15-2005, 09:48 PM   #7
andrewnow
Member
 
Registered: Dec 2004
Location: P.R.C
Posts: 38

Rep: Reputation: 15
Cool try this

//i changed your code as follows:


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

main()
{
FILE *fs;
char ch,d;
char str[20];

if(!(fs=fopen("text","r")))
{
printf("Cant open file!!(Please check that the file is exist or readable)\n");
exit(-1);
}
int i=0;
while((ch=fgetc(fs))!=EOF)
{
if( (ch!='\t') && (ch!='\n'))
{
i=0;
str[i++]=ch;
while((ch!='\t') && (ch!='\n') && (ch!=EOF))
{
ch=fgetc(fs);
str[i++]=ch;
}
str[i]='\0';
func(str);
printf("the sting is=====>>%s\n",str);
}
}
printf("\n");
}

func(char *str)
{
float a;
a=atof(str);
printf("%f\t",a);
}
//it works well in my computer
 
Old 04-16-2005, 03:37 AM   #8
indian
Member
 
Registered: Aug 2004
Posts: 137

Original Poster
Rep: Reputation: 15
thanks Max and Andrew....by the way here is one more question..I frequently needs to read words from some text file and than convert it into Int or Float..

SO now what I want is can I make this a library ? I mean I can definately make it a header file and always include it but can't I include this file in some thing like My_lib.h ?

so whenever I uses #include<My_lib.h> than I can use this code ..I don't want to use this as a header file but as a library.

Thanks again

Last edited by indian; 04-16-2005 at 03:38 AM.
 
Old 04-16-2005, 04:42 AM   #9
andrewnow
Member
 
Registered: Dec 2004
Location: P.R.C
Posts: 38

Rep: Reputation: 15
yes you can

1.change the name of your main() function.as follows:
#include<stdio.h>
#include<string.h>
#include<stdlib.h>
#include<math.h>

void trans_to_float()
{
FILE *fs;
char ch,d;
char str[20];

if(!(fs=fopen("text","r")))
{
printf("Cant open file!!(Please check that the file is exist or readable)\n");
exit(-1);
}
int i=0;
while((ch=fgetc(fs))!=EOF)
{
if( (ch!='\t') && (ch!='\n'))
{
i=0;
str[i++]=ch;
while((ch!='\t') && (ch!='\n') && (ch!=EOF))
{
ch=fgetc(fs);
str[i++]=ch;
}
str[i]='\0';
func(str);
printf("the sting is=====>>%s\n",str);
}
}
printf("\n");
}

func(char *str)
{
float a;
a=atof(str);
printf("%f\t",a);
}

2.compile your code with such command:gcc -c trans_to_float.c
3.edit a header file as it's name is: My_lib.h
4.ar crv My_lib.a trans_to_float.o
5.ranlib My_lib.a
6.it's ok now.you can include this function by #include "My_lib.h"
7.gcc -o yourprogram yourprogram.o Mylib.a
8.ok!



it's called "archive". Many books telled about it. You can find this in "Begining of Linux Programming" by Wrox
 
  


Reply



Posting Rules
You may not post new threads
You may not post replies
You may not post attachments
You may not edit your posts

BB code is On
Smilies are On
[IMG] code is Off
HTML code is Off



Similar Threads
Thread Thread Starter Forum Replies Last Post
What is wrong with the following C code? indian Programming 17 12-04-2005 09:01 AM
What is wrong with this C++ code? frankie_DJ Programming 5 10-01-2005 06:19 PM
What is wrong with this c code? qanopus Programming 3 06-02-2005 10:04 AM
what ' s wrong in code ? phoenix_fei Programming 4 12-17-2004 12:32 PM
What is wrong with this code? qanopus Programming 4 03-12-2004 07:25 AM

LinuxQuestions.org > Forums > Non-*NIX Forums > Programming

All times are GMT -5. The time now is 01:30 AM.

Main Menu
Advertisement
My LQ
Write for LQ
LinuxQuestions.org is looking for people interested in writing Editorials, Articles, Reviews, and more. If you'd like to contribute content, let us know.
Main Menu
Syndicate
RSS1  Latest Threads
RSS1  LQ News
Twitter: @linuxquestions
Open Source Consulting | Domain Registration