gpt4 book ai didi

c - 缓冲区大小问题

转载 作者:太空宇宙 更新时间:2023-11-04 06:25:07 26 4
gpt4 key购买 nike

我写了一个调用 Unix 脚本的 C 程序。该脚本将输出写入通过 POPEN 命令读取的文件。

在读取超过 20 个字符(例如“452088000104023512234”)的输出时,通过现有代码将其转换为一些垃圾字符。

#include <stdlib.h>
#include <stdio.h>

#define OUTPUT_FILE_PATH "/td/mbb/Projects/MBNA/Work/java.txt"
#define SCRIPT_FILE_PATH "/td/mbb/Projects/MBNA/Work/R/TDEncryptDecrypt/TDEncryptDecrypt/src/java.sh"

void waitAndExecuteScript(char* input)
{
char scriptCmd[256];
sprintf(scriptCmd, "%s %s", SCRIPT_FILE_PATH, input);

int i = system(scriptCmd); //execute command string

FILE* fp = fopen ( OUTPUT_FILE_PATH , "rb" );

while (1)
{
if(fp == NULL)
{
usleep(1000);
fp = fopen (OUTPUT_FILE_PATH , "rb" );
}
else
{
fclose(fp);
break;
}
}
}

char * java (char* str1)
{
int i,l;
char * resultval;
char * buffer = NULL;
long lSize = 0;
size_t result = 0;
FILE* pFile = NULL;
char removeCmd[256];

waitAndExecuteScript(str1);

//******************************reading input data in a file ************************

pFile = fopen (OUTPUT_FILE_PATH , "rb" );
if (pFile==NULL)
{
fputs ("File error",stderr);
exit (1);
}

// obtain file size:
fseek (pFile , 0 , SEEK_END);
lSize = ftell (pFile);
rewind (pFile);

// allocate memory to contain the whole file:
buffer = (char*) malloc (sizeof(char)*lSize + 1); // 1 extra byte need to allocate to accomodate null character
if (buffer == NULL)
{
fputs ("Memory error",stderr);
exit (2);
}

// copy the file into the buffer:
result = fread (buffer,1,lSize,pFile);
if (result != lSize)
{
fputs ("Reading error",stderr);
exit (3);
}

/* the whole file is now loaded in the memory buffer. */

buffer[lSize] = '\0'; //make string null terminated so that printf will print it properly
printf("result from script %s", buffer);

resultval = buffer;
// terminate
fclose (pFile);
if(buffer != NULL)
{
free (buffer);
}

//wait here for 1ms
usleep(1000);

return resultval; //Return the result value of the script
}

最佳答案

你似乎在做的是:

  1. 运行一些外部命令来写入文件

  2. 轮询是否可以打开文件(在 waitAndExecuteScript 中)

  3. 紧接着,读取文件(在 java 中)。

这个策略是行不通的。除非您知道外部命令以原子方式创建文件(例如,将其写入不同的文件然后重命名),否则该文件将在完全写入之前存在并变得可读。考虑以下顺序:

  1. 外部进程打开文件进行写入,但尚未写入任何内容

  2. waitAndExecuteScript成功打开空文件

  3. java读取空文件

  4. 外部进程写入数据。

如您所见,数据可能已部分写入。

您应该做的是检查进行写入的进程是否已完成。或者,让它写入管道并使用阻塞读取。

关于c - 缓冲区大小问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28153377/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com