Hi, I got a problem in reading and write on file.
I have to create an virtual agenda, therefore I enter a name and a number for N persons.
After entering the infos if the file doesn't exist, the program create it and save the infos, if the file exist the program will overwrite all the lines.

But when i write on screen the information from a fprintf the lines are messed up.

I load the infos form the file with this:

    fp=fopen("agenda.txt","r");
            if(fp)
            {
                rewind(fp);
                while(!feof(fp))
                {
                    fscanf(fp,"%s %s",inome,inum);
                    if(ii==NULL)
                    {
                        head=malloc(sizeof(agenda));
                        if(!head)
                        {
                            printf("Memory Problems");
                            exit(1);
                        }
                        head->prev=NULL;
                        head->next=NULL;
                        strcpy(head->nome,inome);
                        strcpy(head->num,inum);
                        ii=head;
                        fflush(stdin);
                    }

And i save the info from the memory to the file with this

void save()
{
    fp=fopen("agenda.txt","w");
    ptr ii=head;
    rewind(fp);
    while(ii)
    {
        fprintf(fp,"%s %s",ii->nome,ii->num);
        ii=ii->next;
    }
    fclose(fp);
    return;
}

This is what happens after that the program writes on screen the infos from the file
http://s11.postimage.org/go4n2p48j/save.png

fprintf(fp,"%s %s",ii->nome,ii->num);

The problem is that you have to put '\n' at the end. And your program won't work at all if you put a space in the name that you enter, such as "John Smith" or something like that.
fprintf(fp,"%s %s\n",ii->nome,ii->num);

Edited 4 Years Ago by Ancient Dragon

I feel that it should work fine but some problem is in memory allocation

Edited 4 Years Ago by Rouf mir

I feel that it should work fine but some problem is in memory allocation

Contridction! if there is a prblem then it is not working find :)

This article has been dead for over six months. Start a new discussion instead.