I'm designing a program for appending a few lines at certain line from a file.
the procedure is read from a file & store the lines into a link list, append at certain line then write it to result.txt.
However, my firstline is not working properly.
Code:
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
typedef struct Node {
char line[100];
struct Node *next;
} NodeT;
NodeT *makeNode(char *);
int Append(char *,int);
int main(int argc, char **argv) {
NodeT *head;
NodeT *cur;
NodeT *new;
NodeT *inputhead;
NodeT *inputcur;
NodeT *inputnew;
NodeT *tmp;
NodeT *tmp1;
FILE *fp,*fpo;
int linenum;
char line[100];
int i = 1;
linenum = atoi(argv[1]);
fp = fopen(argv[2],"r");
while(fgets(line,100,fp) != NULL) {
if(i == 1){
head = makeNode(line);
head = cur;
printf("%s",head->line);//shouldn't they print out the same things??
printf("%s",line);
}
else{
new = makeNode(line);
cur->next = new;
cur = cur->next;
}
i++;
}
i = 1;
fclose(fp);
while(1) {
fgets(line,100,stdin);
if(line[0] == '.') break;
if(i == 1){
inputhead = makeNode(line);
inputcur = inputhead;
}
else{
inputnew = makeNode(line);
inputcur->next = inputnew;
inputcur = inputnew;
}
}
i = 1;
cur = head;
while(i < linenum){
tmp = cur;
cur = cur->next;
i++;
}
tmp->next = inputhead;
inputcur->next = cur;
tmp1 = head;
fpo = fopen("result.txt","w+");
while(tmp1 != NULL){
fprintf(fpo,"%s",tmp1->line);
tmp1 = tmp1->next;
}
return 0;
}
NodeT *makeNode(char *line) {
NodeT *new;
new = malloc(sizeof(NodeT));
if (new == NULL) {
exit(1);
}
strcpy(new->line,line);
new->next = NULL;
return new;
}