Запись данных в текстовый файл C++
Имеется текст с кол-вом строке <=100. Я написал две функции для чтения и записи в выходной файл данных в обратном лексикографическом порядке. В рамках функции main все работало, но после создания нескольких функций запись перестала работать. Удалось выяснить, что передается n=0 в функцию write, но даже если указать другое число, цикл заканчиается на первом слове. так ничего и не записав.
Все в единой функции:
#include<iostream>
#include <cstring>
using namespace std;
struct Word
{
char str[90];
};
Word *Sort(Word *obj,int n)
{
Word *data=new Word[n];
for(int i=0;i<n-1;i++)
{
for(int j=n-1;j>i;j--)
{
if(obj[j-1].str[0]<obj[j].str[0])
{
strcpy(data[0].str,obj[j].str);
strcpy(obj[j].str,obj[j-1].str);
strcpy(obj[j-1].str,data[0].str);
}
}
}
delete [] data;
return obj;
}
int main()
{
int n=0;
FILE *input;
Word *obj=new Word[100];
input=fopen(R"(input.txt)","r");
if(!input)
{
cout<<"Unable to open file!\n";
}
else
{
while(!feof(input))
{
fscanf(input,"%s",obj[n].str);
n++;
}
fclose(input);
}
obj=Sort(obj,n);
FILE *output;
output=fopen(R"(output.txt)","w");
if(!output)
{
cout<<"Unable to open output file!\n";
}
else
{
for(int i=0;i<n;i++)
{
fprintf(output,"%s\n",obj[i].str);
}
fclose(output);
}
cout<<"All done!\n\n";
delete [] obj;
return 0;
}
Раздельно:
//main.cpp
#include <iostream>
#include "Funcs.h"
using namespace std;
int main() {
int n = 0;
Word *obj = new Word[100];
read(n, obj);
write(n, obj);
return 0;
}
//Funcs.h
#include <iostream>
#include <cstring>
#include <tuple>
using namespace std;
struct Word {
char str[90];
};
Word *Sort(Word *obj, int n);
tuple<int, Word *> read(int n, Word *obj);
void write(int n, Word *obj);
//Funcs.cpp
#include "Funcs.h"
Word *Sort(Word *obj, int n) {
Word *data = new Word[n];
for (int i = 0; i < n - 1; i++) {
for (int j = n - 1; j > i; j--) {
if (obj[j - 1].str[0] < obj[j].str[0]) {
strcpy(tem[0].str, obj[j].str);
strcpy(obj[j].str, obj[j - 1].str);
strcpy(obj[j - 1].str, data[0].str);
}
}
}
delete[] data;
return obj;
}
tuple<int, Word *> read(int n, Word *obj) {
FILE *input;
input = fopen(R"(input.txt)", "r");
if (!input) {
cout << "Unable to open file!\n";
} else {
while (!feof(input)) {
fscanf(input, "%s", obj[n].str);
cout << "Word:" << obj[n].str << endl;
n++;
}
fclose(input);
}
obj = Sort(obj, n);
return make_tuple(n, obj);
}
void write(int n, Word *obj) {
FILE *output;
output = fopen(R"(output.txt)", "w");
if (!output){
cout << "Unable to open file!\n";
} else {
for (int i = 0; i < n; i++) {
fprintf(output, "%s\n", obj[i].str);
}
fclose(output);
}
delete[] obj;
}