I read txt file with fgets, and save string
and i printf_s this string, but text is broken how can I fix this problem?
int main() {
char name[256] = "";
int a = 0, b = 0, c = 0, d = 0;
FILE *fp = 0;
fopen_s(&fp, "a.txt", "r");
if (fp == 0)
{
printf_s("can't open this file\n");
return 0;
}
std::string st;
fgets(name, 256, fp);
st += name;
printf_s("%s\n", name);
fgets(name, 256, fp);
st += name;
printf_s("%s\n", name);
fgets(name, 256, fp);
st += name;
printf_s("%s\n", st, sizeof(st));
fclose(fp);
return 0;
}
"a.txt"'s text
hello world line 1 text text 2 line 3 line text
and in this code, I fgets several text line in char and add this text in string named st. can I insert all text of using fgets in string directly?
I think what you are looking for is a bit of pointer manipulation, but first:
C++
code into your C
program - std::string
does not belong here.sizeof
on a string
, there will be unexpected consequences. The length of the string is strlen(string)
, and the size is strlen(string)+1
.To keep appending to name
, you can use something like:
fgets(name, 256, fp);
fgets(name+strlen(name), 256-strlen(name), fp);
fgets(name+strlen(name), 256-strlen(name), fp); //Repeat (loop?)
This way you will aggregate the file contents to name
. Each time you are passing a pointer that points to the previous '\0'
character, and overwriting it while making sure you do not read in total more than 256 characters (255 and a '\0'
).
You better make sure that:
fgets
succeeds and does not return NULL
.feof(fp)
is false.name
completely.