hi all,
i am trying to make a prog. which will read the first line of a text file and put the first line into an array and pass the entire array to a function.

Here is my code:

#include <stdio.h>
#include <conio.h>
#include <string.h>
#include <string.h>

void exe(char cmd)
{   
    printf("%c",cmd);
}

int main() 
{
  char st;
  FILE *p;
  char cmd[8];
  p = fopen("test.txt", "rt");
  
  if (p == NULL) 
  {
    printf("File does not exist.\n");
  } 
  else 
  {
       while(1)
       {
               int i;
	           st = fgetc(p);
	           if (st == '\n')
	              break;
               else
	               cmd[i]= st;
	               i++;
       }
  }
  fclose(p);
exe(cmd);
return 0;
}

But the code is not working.Can any one please suggest .

You have doubled lines 3 and 4.
There is max 8 characters read from file with no null termination, then you try to pass it as char parameter to function exe (which should not work), to try to print the letter. I do not get it. You are not trying to pass array to function only char. Generaly arrays are passed by reference not by value.

As for tutorials, this looks very interesting, but does include lot to learn: http://pweb.netcom.com/~tjensen/ptr/pointers.htm

Edited 5 Years Ago by pyTony: n/a

What if the text file contains more than 8 characters before a \n is present? The program will try to store the 9 char at cmd[8] . This will lead to a crash

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