I want to know how I can implement a function to open a file and read its contents into a linked list, and then print the contents reversed

#include <stdio.h>

typedef struct stack
{
char b[100];
int top;
}stack;
void push(stack *s,char k)
{
if(s->top==99)
printf("\n Stack is full ");
else
s->b[++s->top]=k;
}
char pop(stack *s)
{
char c;
if(s->top==(-1))
printf("\n Stack is empty");
else

c=s->b[s->top--];
return c;
}
void main()
{
char name[100];
stack s;
system("clear") ;
s.top=-1;
printf("\nEnter name :");
gets(name);
int i=0;
while(name[i]!='\0')
{
push(&s,name[i]);
i++;
}
printf("\n Reverse string is :");
while(s.top!=-1)
{
printf("%c",pop(&s));
}
getchar();
} 

Do you know how to read a file? If yes then read the file one character at a time and call push() to add the character to the stack, almost exactly like the code you posted does it from the keyboard. It's just a small change for lines 31-38 of your program.

Thank you for your quick response! I changed my main(void) to but am getting the following error
incompatible types when assigning to type 'char[100]' from type 'int'

void main()
{
stack s; 
system("clear") ;
s.top=-1;
char name[100];
FILE *ok;

printf("\nEnter name :");
fd= fopen("test.txt", "rt");
name=fgetc(fd);

if(name ==NULL)
{
printf("Cannot open %s\n");
}

int i=0;

while(name[i]!='\0')
{

push(&s,name[i]);
i++;
}
printf("\n Reverse string is :");
while(s.top!=-1)
{
printf("%c",pop(&s));
}
fclose(fd);
} 

whoops one mistake is File *ok needs to beFILE *fd but it still doesn't fix the problem =/

fgetc() only reads one character, you need to put it in a loop to read all the characters in the file. fd normally means "file descriptor" which is usually an integer. Although it doesn't really matter what you call it, fp (file pointer) is more descriptive and in more common use for the return value of fopen().

int c;
while( (c = fgets(fp)) != EOF)
{

    push(&s,c);
}

Replace lines 18-25 with the above code, then delete variable name[] because it isn't used.

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.