Reputation: 123
I just want to read a file and store it in a array. I tried the following code
#include<stdio.h>
#include<string.h>
#include<fcntl.h>
int main()
{
int fd;
char buffer[500];
fd=open("input.txt",O_RDONLY);
read(fd,buffer,500);
printf("\nTHE FILE CONTENTS ARE:\n%s",buffer);
}
input.txt contains:
COPY START 0000
FIRST STL RETADR
CLOOP JSUB RDREC
LDA LENGTH
COMP #0
JEQ ENDFIL
JSUB WRREC
J CLOOP
ENDFIL LDA =C'EOF'
STA BUFFER
LDA #3
STA LENGTH
JSUB WRREC
J @RETADR
USE CDATA
RETADR RESW 1
LENGTH RESW
USE CBLKS
BUFFER RESB 4096
BUFEND EQU *
MAXLEN EQU BUFEND-BUFFER
when i printing i am getting extra characters at the end.
end line that i get is
MAXLEN EQU BUFEND-BUFFER EQU BUFEND-BUFFER
why is this?how to solve?
Upvotes: 0
Views: 1812
Reputation: 17910
You have a buffer overflow in your code. You fill the char buffer[500];
argument with 500 characters from the file, but then you printf
it with %s
, which expects a zero-terminated string. But buffer
is not zero-terminated, hence printf
will try to read buffer[500]
, buffer[501]
, etc until it finds a zero terminator ('\0'
).
I suggest you define buffer
to be 501 characters long, fill it with 500 characters and set buffer[500]
to '\0'
so that printf
will not attempt to read past buffer[500]
.
Edit: Actually to print only the contents read from the file you should check the return value of the read
call and put the '\0'
character next to last character written into buffer
, e.g.:
int fd;
char buffer[501];
fd = open("input.txt", O_RDONLY);
const ssize_t r = read(fd, buffer, 500);
if (r < 0) {
// Handle error
} else {
buffer[r] = '\0';
printf("\nTHE FILE CONTENTS ARE:\n%s",buffer);
}
See the manual page for read
for more information (man 3p read
).
Upvotes: 2