I receive some parameters that I transform into char
and concatenate to create a string that is written into a .txt
file. I tried adding a 0
at the end of said string as a line terminator. However, when I use file 10.txt
on my ubuntu terminal, I get 10.txt: ASCII text, with no line terminators
What do I need to change in order to add a line terminator?
int main() {
int res;
res = set_value(10, "abc", 3, 2.0);
}
int set_value(int key, char *value1, int value2, double value3) {
char name[1000];
int status;
char line[5000];
char temp[1000];
int n;
// Change directory where we work.
if (chdir("FilesPractice1") == -1) {
perror("Error while changing directories.");
return -1;
}
// Convert key to the name of the file.
snprintf(name, 1000, "%d.txt", key);
// Open the file.
if ((status = open(name, O_RDONLY)) == -1) {
// Since the file doesnt exist, we proceed to create it.
if ((status = open(name, O_WRONLY | O_CREAT, 0666)) == -1) {
perror("Error while creating the tuple.n");
return -1;
}
// Format the key and values to write them into the file.
snprintf(line, 5000, "%d, ", key);
n = strlen(value1);
strncat(line, value1, n);
snprintf(temp, 1000, ", %d, ", value2);
n = strlen(temp);
strncat(line, temp, n);
snprintf(temp, 1000, "%f", value3);
n = strlen(temp);
strncat(line, temp, n);
n = strlen(line);
line[n + 1] = 0;
// Write the values into the file.
write(status, line, strlen(line));
} else {
// Since file already exists, it is considered an error.
perror("Error: key value already exists.n");
return -1;
}
// Close the file.
if (close(status) == -1) {
perror("Error while closing the file.");
return -1;
}
return 0;
}
2
Answers
"ASCII text, with no line terminators" means there is no line ending at the end of the file (CR or LF).
It is not an error, it just describes the content of the file.
If you want to add line terminators as said, instead of:
Change those 2 lines into the line below for LF (Linux convention):
Or if you want both CR and LF (Windows convention):
EDIT: Changed
strncat
intostrcat
.In order to append a newline to the string, just use
strcat(line, "n");
Also note these remarks:
calling
strncat(line, temp, strlen(temp))
is exactly equivalent tostrcat(line, temp)
.you forget to close the file if it already exists.
the
set_value
function should be defined or at least declared before themain
function.There is no reason to use separate calls to
snprintf
in your code, you could simply write:If you must for some reason construct the output line one field at a time, you can simplify the code by keeping track of the position in the output line instead of using separate arrays for the fragments and concatenating them with
strcat
: