Unbuntu 10.04 Geany IDE
I have a sort of a unique problem.
I want to write to a text file using user input with a char array.
But if the user doesn't write the exact number of characters for the array the text file
becomes unreadable.
Say the array is 10 characters long but the user only inputs 6, the compiler adds extra junk
characters to fill the array making it unreadable by my Linux system, kicking an encoding error
when I try to open the file.
So my question is, is it possible to truncate an array?
Declare an array of sufficient size, then get the actual number of characters form user_input and truncate the array to that number.
Or at least how do I get rid of the junk characters my compiler puts in to fill the array?
I tried adding a second array and using strlen on the first one to get the actual number of characters the user inputs, but getting that info into the second array is alluding me.
My code so far:
Code:
#include <stdio.h>
#include <string.h>
int main(int argc, char** argv)
{
char usr_input[10];
int x;
FILE *fp;
fp=fopen("//home//rocko//test.txt", "a+");
printf("Enter text to append to file: ");
scanf( "%s", &usr_input);
x = strlen (usr_input);
if ( x < 10 )
{
char new_str[x];
fwrite(new_str, sizeof(new_str[0]), sizeof(new_str)/sizeof(new_str[0]), fp);
return 0;
}
else
{
fwrite(usr_input, sizeof(usr_input[0]), sizeof(usr_input)/sizeof(usr_input[0]), fp);
}
return 0;