Tony Tannous Tony Tannous - 4 months ago 27
C Question

"no newline at end of file" C

I'm using this command to compile:

gcc –Werror –std=c99 client.c –o client


CODE:

#include <string.h>
#include <stdio.h>
#include <strings.h>
#include <stdlib.h>
#include <unistd.h>
#include <netdb.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>


#define BUFFER_SIZE 1000
#define PORT_NUM 8888

void error(char *msg)
{
perror(msg);
exit(0);
}

int main(int argc, char *argv[])
{
int sockfd, portno, n;

struct sockaddr_in serv_addr;
struct hostent *server;
char buffer[BUFFER_SIZE];

if (argc < 3) {
fprintf(stderr,"usage %s hostname port\n", argv[0]);
exit(0);
}
portno = atoi(argv[2]);

sockfd = socket(AF_INET, SOCK_STREAM, 0);
if (sockfd < 0)
error("ERROR opening socket");

server = gethostbyname(argv[1]);
if (server == NULL) {
fprintf(stderr,"ERROR, no such host\n");
exit(0);
}

bzero((char *) &serv_addr, sizeof(serv_addr));
serv_addr.sin_family = AF_INET;
bcopy((char *)server->h_addr,
(char *)&serv_addr.sin_addr.s_addr,
server->h_length);
serv_addr.sin_port = htons(portno);
if (connect(sockfd,(struct sockaddr *)&serv_addr,sizeof(serv_addr)) < 0)
error("ERROR connecting");

while (1)
{
bzero(buffer, BUFFER_SIZE);
fgets(buffer, BUFFER_SIZE, stdin);
if((strncmp(buffer,"close",5) == 0 ))
break;
printf("Please enter the message: ");
bzero(buffer, BUFFER_SIZE);
n = write(sockfd,buffer,strlen(buffer));
if (n < 0)
error("ERROR writing to socket");
bzero(buffer, BUFFER_SIZE);
n = read(sockfd,buffer, BUFFER_SIZE-1);
if (n < 0)
error("ERROR reading from socket");
printf("%s\n",buffer);
}

close(sockfd);

return 0;

}


Trying to compile it in a shell on VM whos OS is linux
This error is driving me crazy, I don't understand what to do inorder to fix this.
I thought the client.c file is damaged, so I copied and pasted into a new .c file. When that failed, I wrote it from 0 and still getting this error.

Thanks in advance!

Answer

Text processing programs don't always agree on whether a \n character is line separator or line terminator - the difference being whether or not the last line in a file should be followed by a \n character or not.

I've never seen GCC complain about this, but you didn't indicate where the error is actually coming from.

You should be able to correct the situation by simply pressing ENTER after the last line in your file.

Alternatively, you could open, and them save the file using an editor like Vim, which considers it a line terminator.

As a matter of comparison, most UNIX tools also consider \n a line terminator, and include it after the final line. This allows one to cat a file without corrupting whatever follows (e.g. another file, the shell prompt, etc.)