Thread: write a file to stdout

Threaded View

Previous Post Previous Post   Next Post Next Post
  1. #1
    Registered User
    Join Date
    Oct 2018
    Posts
    42

    write a file to stdout

    Just for exercising some new things I've learned, I wrote this [useless] code which does actually the same thing "ls >> ..." does:
    Code:
    #include<stdio.h>
    #include<stdlib.h>
    
    int main()
    {
    
      system("ls > list_of_files.txt");
      FILE *f = fopen("list_of_files.txt", "r");
      char *content;
      fseek(f, 0L, SEEK_END);
      long size = ftell(f);
      rewind(f);
      content = malloc(sizeof(char) * size);
      fread(content, sizeof(char), size, f);
      puts(content);
      printf("%lu\n", size);
    
      return 0;
    }
    however, then I thought that might also be possible to remove some lines by just straightly reading from the file and writing to the stdout. the code inside main:
    Code:
    system("ls -la > list_of_files.txt");
    FILE *f = fopen("list_of_files.txt", "r");
    fseek(f, 0L, SEEK_END);
    long size = ftell(f);
    rewind(f);
    fread(stdout, sizeof(char), size, f);
    which gives an error: segmentation fault(core dump). So I searched this error and it's when OS detects a program is trying to access a memory address that does not belong to it, so where have I done such a thing? Thanks in advance.
    Last edited by Salem; 11-12-2018 at 06:03 AM. Reason: Remove crayola

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. File Positioning stdout
    By rrc55 in forum C Programming
    Replies: 2
    Last Post: 01-20-2010, 12:47 PM
  2. write to a char* instead of stdout
    By markucd in forum C Programming
    Replies: 2
    Last Post: 08-16-2006, 02:27 PM
  3. Who to redirect stdout to a file in C
    By edugarcia in forum Linux Programming
    Replies: 3
    Last Post: 10-01-2004, 12:18 AM
  4. writing stdout to a file
    By SIKCAR in forum C Programming
    Replies: 4
    Last Post: 09-09-2002, 06:35 AM
  5. redirect stdout to a file?
    By Brian in forum C Programming
    Replies: 5
    Last Post: 01-15-2002, 01:06 PM

Tags for this Thread