mrbean
mrbean

Reputation: 581

Concatenating int to char[]

I'm new to C (obviously) and I am getting the following error:

warning: passing argument 2 of ‘strncat’ makes pointer from integer without a cast [enabled by default]

Here is the code:

int main(void)
{
  FILE *fp;
  int c;
  unsigned char file[1024] = "/path/to/file";
  unsigned char text[1024] = "SomeText";

  fp = fopen(file, "r");
  if (fp == NULL)
  {
    perror("Error opening file");
    return(-1);
  }

  while ((c = fgetc(fp)) != EOF && c != '\n')
  {
    strncat(text,c,1);
  }
}

Obviously this makes sense to me but unfortunately not the compiler. How would I write this better?

Upvotes: 1

Views: 1093

Answers (5)

Jonathan Wood
Jonathan Wood

Reputation: 67175

strcat() concatenates two strings, and a C string is an array with a terminating '\0' character. So this is a mismatch.

However, strncat() concatenates two strings and let's you set the maximum number of characters to copy. So you could pass the address of the c and it will be treated like an array with only one element. So you could try something like this:

strncat(text, (char*)&c, 1);

Otherwise, you need a character buffer to hold this stuff.

Upvotes: 1

Farouq Jouti
Farouq Jouti

Reputation: 1667

try this strncat(text, &c,1)

Upvotes: 0

Sergey Kalinichenko
Sergey Kalinichenko

Reputation: 726479

strncat cannot append a character to a string, because it appends strings to strings. You can make a one-character string from your c character, but using strcat is an overkill: you would be better off making a pointer, and appending by adding characters to it:

char *p = &text[strlen(text)]; // Start appending at the last position of text
while ((c = fgetc(fp)) != EOF && c != '\n') {
    *p++ = c;
    if (p == &text[1023]) break;
}
*p = '\0';

Pointer check in the loop has been added to deal with buffer overruns.

Upvotes: 2

Jack
Jack

Reputation: 133557

There is no implicit conversion between an integer and a string representing the value stored in the integer. You must manually convert it.

Function itoa can do it for you:

int value = 1234;
char tempBuffer[MAX_DIGITS];
itoa(value, tempBuffer, 10);

Upvotes: 2

Nick Russo
Nick Russo

Reputation: 1542

strncat is for concatenating (C-style) strings. text is a char[], so that works, but c is an int, which is definitely not a string, hence the error.

Upvotes: 0

Related Questions