Hello every one!Please help me!!
I am new to C programming.I wrote a programe to copy lines one by one of a file to an array.But it cant compile.I cant understand the error code also.Please help me!
here is my code.

#include<stdio.h>
int main()
{
FILE *f;
char data[256]={0};

char c[128]={0};
int i=0;
    if((f=fopen("C:\data.txt","r"))==NULL){
        printf("File cant open....\n");
    }
    else{
        while(fgets(data,50,f)!=NULL){
        printf("data[%d]:%s",i,data);
        c[i]=strdup(data);
        sprintf(c[i],data);
        i++;

        }

        fclose(f);
    }
}

Recommended Answers

All 8 Replies

Use a forward slash; #include necessary headers.

What error does the compiler give?

Use a forward slash; #include necessary headers.

OK. While we're at it - other things to consider:

1) you are not returning a value - main() returns an int.

2) your strdup() and sprintf() function calls are all wrong. Have you studied how these functions work? With strdup(), you are trying to assign the return string to a character!

3) sprintf() parameters are wrong. This function is similar to printf() except that the output is stored in the character array. I'm not sure why you even want to do this considering that you've called strdup() in the previous line. It's either one or the other.

4) I think your logic is a "bit off". It seems like you want to read a line from your file and assign each line to an element of your array - an array of strings. If this is the case, then your declaration for c needs to be an array of pointer to char - char *c[128]. And then you'll have to allocate memory for each pointer as well before pointing it anywhere.

Thanks very much for all replys.I just need to get line by line from the file and input it to an array.I use VS 2008.

int main()
{
FILE *f;
char data[256];

char c[128]={0};
int i=0;
    if((f=fopen("C:\data.txt","r"))==NULL)
{       printf("File cant open....\n");
    }
    else{
        while(fgets(data,50,f)!=NULL){
        c[i] = strdup(data);
        printf("String:%s",c[i]);
        i = i + 1;
        }
        fclose(f);
    }
}

It cant compile.the error is as below.

Unhandled exception at 0x6b7d18a8 in project3.exe: 0xC0000005: Access violation reading location 0xfffffff0.

You have obviously paid no attention to any advice given to you. You have not formatted your code and ignored advice on how to fix your code provided by Dave Sinkula and me.

Well good luck buddy!

why dont u use fgetc and put str[c]=c; ?

Thanks Yellow Snow for great advices.Finally I was able to solve the problem.I am new to this forum.Very sorry for the mess.The mistake was at array declaration it should be like "char *c[128]"
and need to allocate memory.Again and again thanks very mush for all.

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.