我想读取文件的内容并打印其内容的反面。仅使用fopen,fgets,fputs,fclose。这是我所做的,但是什么也没打印。
string s = "23031";
stringstream test(s);
int x = 0;
test>> x;
// Now the variable x holds the value 23031
cout << "Value of x : " << x;
输出:
#include <sys/types.h>
#include <sys/stat.h>
#include <sys/fcntl.h>
#include <unistd.h>
#include <stdio.h>
int main(int argc, char *argv[])
{
if (argc != 2)
{
return 1;
}
FILE *f = fopen(argv[1], "r");
if (f == NULL)
{
return 2;
}
char buffer[4096];
char reversed[4096];
char *line = fgets(buffer, 50, f); //read 50 characters at a time
int length = 0;
int j = 0;
while (line != NULL) // while end of file not reached
{
length = 0;
j = 0;
for (char *temp = buffer; *temp != '\0'; temp++) //find length of buffer
{
length += 1;
}
for (int i = length; i > 0; i--) // reverse buffer
{
reversed[j] = buffer[i];
j += 1;
}
fputs(reversed, stdout);
line = fgets(buffer, 50, f);
}
fclose(f);
return 0;
}
示例:
(nothing)
预期输出:
abcdef
ghi
答案 0 :(得分:1)
您从错误的偏移量开始
for (int i = length; i > 0; i--) // reverse buffer
切换到
for (int i = length - 1; i >= 0; i--) // reverse buffer
否则,您交换/反转NUL终止符并得到一个空字符串