PDA

View Full Version : سوال: نحوه ی اجرای main آرگومان دار



feri88
جمعه 29 خرداد 1388, 11:39 صبح
سلام
من یه برنامه واسه ایجاد یه فایل از کتابخونه msdn برداشتم که اینجا گذاشتم:




#include <Windows.h>
#include <tchar.h>
#include <stdio.h>

#define BUF_SIZE 80

HANDLE hFile;

void __cdecl _tmain(int argc, TCHAR *argv[])
{
DWORD dwBytesRead;
char buf[BUF_SIZE];

printf("\n");
if( argc != 2 )
{
printf("ERROR:\tIncorrect number of arguments\n\n");
printf("%s <file_name>\n", argv[0]);
return;
}

hFile = CreateFile(argv[1], // file to open
GENERIC_READ, // open for reading
FILE_SHARE_READ, // share for reading
NULL, // default security
OPEN_EXISTING, // existing file only
FILE_ATTRIBUTE_NORMAL, // normal file
NULL); // no attr. template

if (hFile == INVALID_HANDLE_VALUE)
{
printf("Could not open file (error %d)\n", GetLastError());
return;
}

if(!ReadFile(hFile, buf, BUF_SIZE, &dwBytesRead, NULL))
{
printf("Could not read from file (error %d)\n", GetLastError());
return;
}
buf[dwBytesRead]='\0';
printf("Read from file: %s\n", buf);
}



وقتی اجرا می کنم، تو صفحه کنسول اینو نشون می ده:



ERROR: Incorrect number of arguments

e <file_name<
Press any key to continue . . .


بعدش اومدم توی محیط CMD ، اول دایرکتوری جاری رو به دایرکتوری حاوی فایل exe تغییر دادم و دستور زیر رو توش نوشتم:



createfile.exe myfile.txt


ولی دوباره ارور داد:


E:\Documents and Settings\Comp\My Documents\Visual Studio2008\Projects\creat
efile\Debug>createfile.exe myfile.txt

Could not open file (error 2)


یعنی نمی تونه فایل رو ایجاد کنه!

بی زحمت بگین آیا دستور ایجاد فایلم توی cmd اشکال داره یا مشکل چیز دیگه اس؟
بعدش موقع ایجاد فایل حتما باید بسوندشم بدیم؟
و اگه ممکنه یه توضیح کوچولو در مورد main آرگومان دار؟

با تشکر فراوان

tdkhakpur
جمعه 29 خرداد 1388, 13:32 عصر
سلام
اصلاح کنید


void __cdecl _tmain(int argc, TCHAR *argv[])
.
.
.
void main(int argc, TCHAR *argv[])

PC2st
جمعه 29 خرداد 1388, 14:07 عصر
hFile = CreateFile(argv[1], // file to open
GENERIC_READ, // open for reading
FILE_SHARE_READ, // share for reading
NULL, // default security
OPEN_EXISTING, // existing file only
FILE_ATTRIBUTE_NORMAL, // normal file
NULL); // no attr. templateدر تابع بالا از ثابت OPEN_EXISTING استفاده شده، پس فقط فایل‌هایی که از قبل موجود باشه رو باز می‌کنه که خودش هم بطور توضیح جلوش نوشته.


بعدش موقع ایجاد فایل حتما باید بسوندشم بدیم؟قاعدتا اینطوره.


و اگه ممکنه یه توضیح کوچولو در مورد main آرگومان دار؟
علاوه بر توضیحی که جناب tdkhakpur دادند، برای مثال:

#include <stdio.h>

int main (int args, char** argv)
{
int i;
for (i = 0; i < args; ++i)
{
printf ("%s\n", argv [i]);
}
return 0;
}