LinuxQuestions.org

LinuxQuestions.org (/questions/)
-   Programming (https://www.linuxquestions.org/questions/programming-9/)
-   -   Read a txt file in C (https://www.linuxquestions.org/questions/programming-9/read-a-txt-file-in-c-593464/)

xeon123 10-21-2007 10:23 AM

Read a txt file in C
 
hi,

I start to hate C, because I don't understand what's going on inside the primitives functions.

Why this example, doesn't read a txt fil.e The temp.txt exists and it's in the same path has the C file.


Code:


void redirect_in(char* cmd, char* file)
{
  int i;
  int thisin;
  int pid[2];
  //  unsigned char *buffer;
  char *data;
  int fileLen;

  FILE* fd;
  fd = fopen("./temp.txt", "r");

  //  pipe( pid );

  //int fint = fork();
  //if ( fint == 0 )
  //  {
      //dup2( fd, fileno( stdin ));// to read
      //dup2( pid[1], fileno( stdout ));// to write

  fseek(fd, 0, SEEK_END);
  fileLen=ftell(fd);
  printf("%d\n", fileLen);
  data = (char*) malloc(fileLen + 1);
  //fread(buffer, fileLen, 1, fd);
  //while (feof(fd) == 0)
  //  {
  //  fgets(data, 10, fd);      /* Read next record                    */
  while(fgets(data, 80, fd) != NULL)
  {
    /* get a line, up to 80 chars from fr.  done if NULL */
    sscanf (data, "%s");
    /* convert the string to a long int */
    printf ("%s\n", data);
  }

Any help?

The C is killing me, because I don't understand what's going on.

b0uncer 10-21-2007 10:47 AM

I'd start off by taking the file reading procedure into it's own .C file (minimal main() to test it), compile it and see if it works or not. When it works, then just move the code into your bigger program..

Also if it's in the same directory, you don't need "./filename.txt", "filename.txt" should do just fine.

EDIT: something like
Code:

#include <stdio.h>
int main(void)
{
  FILE* fd;
  int c;

  fd = fopen("somefile.txt", "r");
  while ((c = getchar()) != EOF);
      printf("%d", c);
  fclose(fd);
  return 0;
}

If the above snipplet contains errors, don't blame me, I wrote it off the top of my head and honestly I can't say I'll remember everything 100% correctly.. :)

reverse 10-21-2007 10:56 AM

Code:

  while(fgets(data, 80, fd) != NULL)
  {
    /* get a line, up to 80 chars from fr.  done if NULL */
    sscanf (data, "%s");
    /* convert the string to a long int */
    printf ("%s\n", data);
  }

What is that "sscanf(data, "%s");" supposed to do? And.. "convert the string to a long int" <-- WTH!?

xeon123 10-21-2007 11:14 AM

Thank you for the help.


All times are GMT -5. The time now is 10:50 PM.