多个strcat无法正常工作

时间:2013-12-11 16:45:17

标签: strcat

我过去几天一直试图修复此代码,但它不会工作..

char* appdata = getenv("APPDATA");
char* firstloglocation = strcat(appdata, "\\path\log1.txt");

这是有效的,但我需要这个:

char* appdata = getenv("APPDATA");
char* firstloglocation = strcat(appdata, "\\path\log1.txt"); 
char* secondloglocation = strcat(appdata, "\\path\log2.txt");

一旦我添加第二行代码,它就什么都不做了

这两个日志都必须上传到我的FTP服务器,其余代码工作正常

以下是原始代码:

#include <windows.h>
#include <tlhelp32.h>
#include <tchar.h>
#include <wininet.h>
#include <ctime>
#include <iostream>
#pragma comment(lib, "wininet")

int WINAPI WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, LPSTR lpCmdLine, int nCmdShow)
{
    srand((unsigned)time(NULL));
    int seedone=rand();
    int seedtwo=rand()*3;
    int seedboth = seedone + seedtwo;
    char randomnumber[99];
    itoa(seedboth, randomnumber, 10);
    char* appdata = getenv("APPDATA");
    char* log1 = strcat(appdata, "\\DVcA\\log.txt"); // Location of the first log
    char* log2 = strcat(appdata, "\\DVcB\\log.txt"); // Location of the second log
    HINTERNET hInternet;
    HINTERNET hFtpSession;
    hInternet = InternetOpen(NULL, INTERNET_OPEN_TYPE_DIRECT, NULL, NULL, 0);
    hFtpSession = InternetConnect(hInternet, "SERVER", INTERNET_DEFAULT_FTP_PORT, "USERNAME", "PASSWORD", INTERNET_SERVICE_FTP, 0, 0); // Server details
    FtpCreateDirectory(hFtpSession, "DVcA"); // Create directory
    FtpSetCurrentDirectory(hFtpSession, "DVcA"); // Go to folder
    FtpPutFile(hFtpSession, log1, randomnumber, FTP_TRANSFER_TYPE_BINARY, 0);
    FtpSetCurrentDirectory(hFtpSession, ".."); // Go back to root folder
    FtpCreateDirectory(hFtpSession, "DVcB"); // Create directory
    FtpSetCurrentDirectory(hFtpSession, "DVcB"); // Go to folder
    FtpPutFile(hFtpSession, log2, randomnumber, FTP_TRANSFER_TYPE_BINARY, 0);
    InternetCloseHandle(hFtpSession);
    InternetCloseHandle(hInternet);
    return 0;
}

1 个答案:

答案 0 :(得分:2)

strcat修改其第一个参数,然后返回它。因此,当您第二次拨打appdata时,strcat将不是原始字符串。例如:

  strcpy (str,"these ");
  strcat (str,"strings ");
  strcat (str,"are ");
  strcat (str,"concatenated.");
  // str = these strings are concatenated.

另一个问题是因为第二个参数被复制到第一个参数中,appdata必须是一个足以容纳字符串的缓冲区。

char appdata[100] = "hey";  
char* firstloglocation = strcat(appdata, " there");   
char* secondloglocation = strcat(appdata, " thar"); 
printf("%s", appdata); // hey there thar

解决方案:

char appdata[100];
strcpy(appdata, getenv("APPDATA"));
char firstloglocation[100];
char secondloglocation[100];
strcpy(firstloglocation, appdata);
strcpy(secondloglocation, appdata);
strcat(firstloglocation, " there");
strcat(secondloglocation, " thar");
printf("%s\n%s", firstloglocation, secondloglocation);

由于您有三个字符串,因此需要三个缓冲区。您可以使用strcpy来避免修改appdata。然后,您可以使用strcat相应地修改字符串。