2014-11-28 3 views
0

Я искал на месте в течение последних нескольких часов, пытаясь найти ответ для этого, но у меня есть функция, предназначенная для получения размера файла одного из аргументов командной строки, но при этом мой дескриптор постоянно возвращал недопустимое значение. Если кто-то хочет помочь мне, это будет очень признательно. Мой код функции выглядит следующим образом:C Программирование-FindFirstFile return Invalid_handle_value

int getSmallFileLength(const char *fileName, WIN32_FIND_DATA data) 
{ 
HANDLE handle = FindFirstFile(&fileName, &data); 
int fileSize = data.nFileSizeLow; 

if (handle == INVALID_HANDLE_VALUE) 
{ 
    printf("\nyou got an error."); 
    return -1; 
} 
else 
{ 
    printf("\nyour file size is %s", fileSize); 
} 

return fileSize; 
} 

Если основной код поможет решить эту проблему я отправлю его, но в это время я очистка беспорядка, который он должен сделать его доступным для чтения. Он передается в моей переменной Win32_find_data и в файле.

Я также использую Visual Studio 2013.

и здесь был основной код прямо сейчас:

#pragma warning (disable:4996) 
    #include <Windows.h> 
    #include <stdio.h> 
    #include <string.h> 
    #include <stdlib.h> 
    #include "cA5_proto.h" 

    int main(int argc, char *argv[]) 
    { 
    int x; 
    int argNum = 1; 
    int counter = 0; 

printf("Command: %s\n", argv[0]); 
for (argNum = 1; argNum < argc; argNum++) 
{ 
    printf("arg #%d: %s\n", argNum, argv[argNum]); 
} 

if (argc != 2) /* argc should be 2 for correct execution */ 
{ 
    /* We print argv[0] assuming it is the program name */ 
    printf("usage: %s filename", argv[0]); 
} 
else 
{ 

    // We assume argv[1] is a filename to open 
    FILE *file = fopen(argv[1], "rb"); 
    FILE *fileOutput = fopen("contents.txt", "a"); 
    WIN32_FIND_DATA fileData = { 0 }; 
    getSmallFileLength(file,fileData); 

    /* fopen returns 0, the NULL pointer, on fnailure */ 
    if (file == 0) 
    { 
     printf("Could not open file\n"); 
    } 
    else 
    { 


      /* read one character at a time from file, stopping at EOF, which 
      indicates the end of the file. Note that the idiom of "assign 
      to a variable, check the value" used below works because 
      the assignment statement evaluates to the value assigned. */ 

     //getSmallFileLength(argv[1]);    //getSmallFileLength outputs either the file size or an error 

     printf("\nThe contents are: \n"); 
     while ((x = fgetc(file)) != EOF) 
     { 
               //IN A FOR LOOP FOR THE LENGTH OF THE FILE SIZE HELPS OUTPUT A \N EVERY 10 CHARACTERS 

      if (counter > 0) 
      { 
       if (counter == 10 || counter % 10 == 0) //SEPERATE LINES WITH A \N EVERY TEN 
       { 
        fprintf(fileOutput, "\n"); 

       } 
      } 

      if (x>10 && x<100)     //puts a zero in front of two digit numbers in the contents output file 
      { 
       fprintf(fileOutput, "0"); 
      } 
      fprintf(fileOutput, "%d ",x); 



      printf("%c", x); 
      counter++; 

     } 
     printf("\n"); 

     //CLOSE FILES HERE 
     fprintf(fileOutput, "\n");    //PUT A \N AT THE END OF THE FILE 
     fclose(fileOutput); 
     fclose(file); 
    } 
} 
return 0; 

} 

Единственное предупреждение я получаю от VSB является следующее: Предупреждение
1 предупреждение C4133: ' функция»: несовместимые типы - от 'FILE *' до 'сопзЬ символ *'

+0

Это _все_ код, который вы показать нам? и не является 'C++'? –

+2

'FindFirstFile (& имя_файла и данные)' -> 'FindFirstFile (имя_файла и данные)' – BLUEPIXY

+1

Компилятор должен предоставить вам хотя бы предупреждение для 'HANDLE handle = FindFirstFile (& fileName, &data);' –

ответ

0

попробовать небольшой тест код

#include <windows.h> 
#include <stdio.h> 

int main(int argc, char *argv[]){ 
    WIN32_FIND_DATA FindFileData; 
    HANDLE hFind; 
    printf ("Target file is %s.\n", argv[1]); 
    hFind = FindFirstFile(argv[1], &FindFileData); 
    if (hFind == INVALID_HANDLE_VALUE) { 
     printf ("Invalid File Handle. Get Last Error reports %d\n", GetLastError()); 
    } else { 
     printf ("The first file found is %s\n", FindFileData.cFileName); 
     printf ("The first file size is %d\n", FindFileData.nFileSizeLow); 
     FindClose(hFind); 
    } 
    return 0; 
} 

FindFirstFile

+0

Этому удалось найти размер файла, так что спасибо, я посмотрю, как я могу идти оттуда, я думаю. –

0
per this link: 
<http://msdn.microsoft.com/en-us/library/windows/desktop/aa364418%28v=vs.85%29.aspx> 
the returned value, when equal to INVALID_HANDLE_VALUE means the file was not found. 

in looking at your code, your passing the address of the address of the filename string 
(a meaningless value) 
what should be passed is 'filename' not '&filename' 
+0

привет благодарю вас за то, что вы нашли время, чтобы ответить, что это была опечатка, когда я был расстроен, мне жаль, что –

Смежные вопросы