Консультация № 70261
10.01.2007, 09:11
0.00 руб.
0 2 2
Здравствуйте! У меня вопрос похож на вопрос № 69.504. Допустим имеем файл в котором имеем 10 строк (столбиком), т.е в моем случае 10 разных текстовых сообщений длиной в 50 символов максимум. Мне необходимо в разных случаях брать готовую строку и выводить ее уже дальше. Как обращаться к отдельной строке?

Обсуждение

Неизвестный
10.01.2007, 09:26
общий
это ответ
Здравствуйте, Holyman!

Навскидку два ответа...
#include <fstream>

ifstream inf;
inf.open(...);
inf.seekg (0, ios::beg);

// 1)
in.seekg(...);
in.getline(..);
// end

// 2) нужна 5-я строка
char str[50];
n = 5;

for(int i=0; i < (n-1); i++) // Сдвигаемся к нужной строке
{
in.getline(str, 50);
}

in.getline(str, 50); // читаем нужную строку (было бы неплохо результирующую обнулить прежде

// end
Неизвестный
10.01.2007, 09:26
общий
это ответ
Здравствуйте, Holyman!

Прототип функции чтения строки из текстово-типизированного файла:

char *fgets(char *s, int n, FILE *stream);

Remarks:
fgets reads characters from stream into the string s. It stops when it reads
either n - 1 characters or a newline character, whichever comes first.

fgets retains the newline character at the end of s and appends a null byte
to s to mark the end of the string.

Return Value:
■ On success,
■ fgets returns the string pointed to by s.
■ fputs returns the last character written.
■ On end-of-file or error, fgets returns null.
■ On error, fputs returns EOF.

Portability:
╔ DOS ╤ UNIX ╤ Windows ╤ ANSI C ╤ C++ Only ╗
║ Yes │ Yes │ Yes │ Yes │ ║
╚═════╧══════╧═════════╧════════╧══════════╝

See Also:
cgets gets puts fputs

Пример использования - в приложении.
Если с буржуйским - проблемы, могу перевести на великий и могучий.


Приложение:
#include <string.h>#include <stdio.h>int main(void){ FILE *stream; char string[] = "This is a test"; char msg[20]; /* open a file for update */ stream = fopen("DUMMY.FIL", "w+"); /* write a string into the file */ fwrite(string, strlen(string), 1, stream); /* seek to the start of the file */ fseek(stream, 0, SEEK_SET); /* read a string from the file */ fgets(msg, strlen(string)+1, stream); /* display the string */ printf("%s", msg); fclose(stream); return 0;}
Форма ответа