-2
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

char buf[32];

int main(int argc, char* argv[], char* envp[]){
    if(argc<2){
            printf("pass argv[1] a number\n");
            return 0;
    }

    int fd = atoi(argv[1]) - 0x1234;
    printf("%d\n", fd);
    int len = 0;
    len = read(fd, buf, 32);
    printf("%s", buf);
    return 0;
}

This my code but I cant print buff. Because read function does not terminate. Please help what is wrong? I run a program from terminal like this:
./fd 4660

Maksim Kevin
  • 71
  • 1
  • 8
  • 1
    I fail to see where do you open your file descriptor? – ouah Dec 25 '14 at 14:35
  • 1
    I'd start by actually opening a file first. The file descriptor is an integer, yes. But you can't just pass any integer to read, it must be an open file, and `atoi` doesn't open files. – datenwolf Dec 25 '14 at 14:35
  • 1
    `./fd 4660` Maybe you are reading stdin (and blocking) ? – wildplasser Dec 25 '14 at 14:36
  • you are reading from fd 0 which is stdin. you need to terminate your input by a linebreak. did you type a line ? – tristan Dec 25 '14 at 14:48
  • @Maksim - you are also ignoring the return value from `read`. That's how the function tells you if it succeeds or fails. That's usually important for I/O functions. – jww Dec 25 '14 at 15:54
  • Possible duplicate of [Reading from stdin](http://stackoverflow.com/questions/15883568/reading-from-stdin). Its a good question/answer because you are given sample code for three ways to do it with caveats and warnings. – jww Dec 25 '14 at 15:56
  • Your line to determine `fd` makes no sense at all. Where did you get that from? What are you trying to achieve? – Jens Gustedt Dec 25 '14 at 17:10
  • What is the meaning of **envp** parameter? What value can we pass to this variable in terminal? I know first we must open the file but I dont have permission to change the content of program above.(Also no permission to change permisions :) ). Therefore is there any way opening file during givin parameter to **main** funciton – Maksim Kevin Dec 29 '14 at 17:17

1 Answers1

1

Where is your file opened? Before reading or writing to your file make sure the file is opened with proper permissions

And please check for the return value of read also.

Check the below link: http://gd.tuwien.ac.at/languages/c/programming-bbrown/c_075.htm

IMO have

printf("%s\n", buf);
Gopi
  • 19,784
  • 4
  • 24
  • 36