Главная страница
Top.Mail.Ru    Яндекс.Метрика
Текущий архив: 2008.12.21;
Скачать: CL | DM;

Вниз

Почему не работает программа   Найти похожие ветки 

 
Костик   (2008-11-11 09:28) [0]


program Project1;

{$APPTYPE CONSOLE}

uses
Windows,
SysUtils;

var
h:THandle;
buf:Array [0..1023] of Char;
n:Cardinal;
f:textfile;
i:integer;
begin
h:=GetStdHandle(STD_INPUT_HANDLE);
Repeat
If Not ReadFile(h,buf,SizeOf(buf),n,Nil) Then Raise Exception.Create("íó åïòà");
Write(buf);
Until n<>SizeOf(buf);
AssignFile(f, "report.txt");
try
 Reset(f);
except
 Rewrite(f);
end;
try
  for i := 0 to n - 1 do
    Write(f,buf[i]);
finally
end;
Flush(f);
CloseFile(f);
end.

При передачи во входной поток данных Windows сообщает что в программе обнаружена ошибка и она будет закрыта. Где тут ошибка?


 
Сергей М. ©   (2008-11-11 09:43) [1]

When a synchronous read operation reaches the end of a file, ReadFile returns TRUE and sets *lpNumberOfBytesRead to zero. The following sample code tests for end-of-file for a synchronous read operation:

// attempt a synchronous read operation  
bResult = ReadFile(hFile, &inBuffer, nBytesToRead, &nBytesRead, NULL) ;
// check for eof
if (bResult &&  nBytesRead == 0, ) {
// we"re at the end of the file
}


 
Сергей М. ©   (2008-11-11 10:01) [2]


program TestConsole;

{$APPTYPE CONSOLE}

uses
 Windows, SysUtils;

var
 h:THandle;
 buf:Array [0..1023] of Char;
 n:Cardinal;
 f:textfile;
 i:integer;
begin
 h:=GetStdHandle(STD_INPUT_HANDLE);
 AssignFile(f, "report.txt");
 try
   try
     Append(f);
   except
     Rewrite(f);
   end;
   try
     while True do
     begin
       Win32Check(ReadFile(h,buf,SizeOf(buf),n,Nil));
       if n = 0 then
         Break;
       buf[n] := #0;
       Write(f,buf);
     end;
   finally
     Flush(f);
     CloseFile(f);
   end;
 except
//  обработка исключений
 end;
end.


 
Костик   (2008-11-11 10:28) [3]

Большое спасибо. Вы настоящий друг.
Ощибка теперь не появляется но и файл не создается.
Из консоли да, но когда ее вызвает функция библиотеки dll то не работает.
Другая программа, которая работает, испльзует конструкцию:

mymessage := "";
while (not eof(Input)) do
begin
  readln(Input, s);
  messageContent := mymessage + s + #13#10;
end;


 
Сергей М. ©   (2008-11-11 10:41) [4]

Цикл вида

while (not eof(Input)) do
begin
  readln(Input, s);
  ..
end;


принципиально ничем не отличается от цикла вида

while True do
begin
 Win32Check(ReadFile(h,buf,SizeOf(buf),n,Nil));
 if n = 0 then
    Break;
 buf[n] := #0;
 ...
end;


И здесь и там выполняется построчное чтение из стандартного потока ввода, до тех пор пока во вх.потоке не обнаружен EOF


 
Костик   (2008-11-11 10:53) [5]

Вот ё-маё, а что же тогда за проблема.
Вот в этой программе ничего особенного, может кроме того, что она запускается с ключом  -t:

// check parameters to make sure "-t" was provided

found := False;
for i := 1 to ParamCount do
  if (ParamStr(i) = "-t") then
  begin
    found := True;
    break;
  end;

if (not found) then
begin
  writeln(ErrOutput, "sendmail requires -t parameter");
  halt(1);
end;

// read email from stdin

messageContent := "";
while (not eof(Input)) do
begin
  readln(Input, s);
  messageContent := messageContent + s + #13#10;
end;

// make sure message is CRLF delimited

if (pos(#10, messageContent) = 0) then
  messageContent := stringReplace(messageContent, #13, #13#10, [rfReplaceAll]);

if (debugLogFile <> "") then
begin
  debugLog("--- MESSAGE BEGIN ---");
  sl := TStringList.Create;
  try
    sl.Text := messageContent;
    for i := 0 to sl.Count - 1 do
      debugLog(sl[i]);
  finally
    sl.Free;
  end;
  debugLog("--- MESSAGE END ---");
end;

debugLog просто пишет в файл... Свою я запускаю без ключа. Вот незадача то...


 
Сергей М. ©   (2008-11-11 11:02) [6]


> Костик   (11.11.08 10:53) [5]


Ну используй тогда этот код, раз он работает, в чем проблема-то ?
Не понятно ..



Страницы: 1 вся ветка

Текущий архив: 2008.12.21;
Скачать: CL | DM;

Наверх




Память: 0.48 MB
Время: 0.015 c
2-1225841336
Семен Кевларвестов
2008-11-05 02:28
2008.12.21
Не срабатывает кейсоинсенситивность в tDataSet.Locate


15-1224238625
TUser
2008-10-17 14:17
2008.12.21
Вопрос к геймерам


15-1222772997
Раиса
2008-09-30 15:09
2008.12.21
Хочу найти работу в Санкт-Петербурге


2-1226415188
Maksim
2008-11-11 17:53
2008.12.21
Изменение размера шрифта в поле Memo


2-1226216765
hinst
2008-11-09 10:46
2008.12.21
TMethod