Problems with input / output files in C

I am writing a version of the Unix utility expandthat replaces tabs with spaces in a file. To do this, I read each character and check if it is a tab character. If so, it replaces the tab with the specified number of spaces, otherwise the character is printed.

My main method is like

int main(int argc, char *argv[]){
 FILE *fp;

 char *help1="-help";
 char *help2= "--help";

 //int spaces; //number of spaces to replace tabs

 fp= fopen(argv[1], "rw");
 parse_file(fp, 4);
 fclose(fp);

 return 0;
}

parse_file method is similar to

void parse_file(FILE *fp, int spaces)
{
  int i; //loop counter
  char c; //current character
  while (c!= EOF)
{
    c= getchar(); //get char from stream

    if (c=='\t') //if char is a tab
    {
        for (i=0; i< spaces; i++)
            putchar(" "); //replace with spaces

    } 
    else 
        putchar(c); //otherwise, print the character

}

}

When compiling, I get an integer from the pointer without warning warning for putchar(" ");, and when the program runs, segfault occurs.

So my questions are:

1- What is the warning "does an integer from a pointer without a cast"? What can I do to solve this problem?

2- segfault , . - , ?

+3
6
  • putchar (" "), char (' '). ( int, char .)

  • , , fclose fp, NULL. fopen. , parse_file, , fp ( stdin stdout). fp, getc(fp) putc(fp). ( , , , .)

, segfault, . fopen segfaults, argv[1], .

, , Unix filters: stdin, stdout. , .

+5

putchar(' ')

putchar(" ")
+8

C char *, , . " " - , . ' ',

+4

, . char . , , . , , int. char ints.

+1

( , , s 5 6 ):

  • putchar() , int - ' '
  • , argc > 1 argv[1]
  • , fopen()
  • c int, (char) -1 (0xFF) , c == EOF , c
  • c EOF . C

    int c;
    while ((c = fgetc(fp)) != EOF)
    { 
        // do stuff with c
    }
    
  • stdin, fp, fgetc() not getchar()

, .

To answer your explicit question, you will get a warning “makes an integer from a pointer without a cast” when an int is expected, but you use a pointer (in this case the type " "is equal const char*).

+1
source

In addition to what has already been said, getchar () returns int not char. EOF is an int constant. You will need to read the result of getchar () in int, check EOF, and if you can not find it, enter int in char.

0
source

Source: https://habr.com/ru/post/1791241/


All Articles