c - Reading a file from stdin -


it's been years since programmed in c, , i've been struggling lot "get filename & path stdin, read file, print file stdout" task, know shouldn't hard ya. here code:

#include <stdio.h> #include <unistd.h> #include <stdlib.h>  int main(void) {     int c;     file *file;     //scanf("%s", filename);     char *filename;     filename = (char *)malloc(200 * sizeof(char));      read(stdin_fileno, filename, 200);       printf("%s", filename);      file = fopen(filename, "r");      if (file) {         while ((c = getc(file)) != eof)             putchar(c);         fclose(file);     } else {         printf("file not found.");     }     printf("\n");      return(0); } 

i code continues print out file not found., when know fact file path , correct (not because literally drop , past terminal folder mac osx el capitan - lovely feature, also) because had different version of program using scanf found file , read fine, (as can see have commented out on code).

there program i'm writing uses one, , got rid of scanf because think negatively affecting other things in program, want able use read()

if has advice on how can fix or why isn't working, appreciated i've been @ hours , move on actual program need code!

thanks bunch

you must remove '\n' new line character being read , stored filename buffer.

one of many include string.h , after reading filename

char *newline = strchr(filename, '\n'); if (newline != null)     *newline = '\0'; 

also, use fgets() instead of read() because way program more portable. , more importantly, read() not add null terminator important in order use buffer string — to pass fopen() example — correctly. if want use read try this

ssize_t length; char filename[200]; length = read(stdin_fileno, filename, sizeof(filename) - 1); if (length <= 0)     return -1; // no input or input error if (filename[length] == '\n')     filename[--length] = '\0'; else     filename[length] = '\0'; 

but otherwise, try simpler

#include <stdio.h> #include <unistd.h> #include <stdlib.h>  #include <string.h>  int main(void)  {     file *file;     char filename[200];     char *newline;         if (fgets(filename, sizeof(filename), stdin) == null)         return -1; // input error / eof     newline = strchr(filename, '\n');     if (newline) // ? newline present?         *newline = '\0';     printf("**%s**\n", filename); // ** checking                                   //    presence of white spaces.      file = fopen(filename, "r");     if (file) {         int chr;         while ((chr = fgetc(file)) != eof)             fputc(chr, stdout);         fclose(file);     } else {         printf("file not found.");     }     printf("\n");      return 0; } 

Comments

Popular posts from this blog

scala - 'wrong top statement declaration' when using slick in IntelliJ -

c# - DevExpress.Wpf.Grid.InfiniteGridSizeException was unhandled -

PySide and Qt Properties: Connecting signals from Python to QML -