输入文件每行有一个条目,格式为T S,其中T是到达时间,S是要读取的扇区。 我有一个file.txt,它看起来像
1 6 2 7 3 8
将指示扇区6,7和8分别在时间1 2和3到达的三个磁盘访问。
我如何解析它,以便第一个数字转到T,第二个转到S?
答案 0 :(得分:0)
有很多方法可以完成这项任务。
以上方法列表并非完整。 许多其他方法可以完成任务。
当然,您可能已经对这些常用方法有了全面的了解,并且您正在寻找具有一些 zing的东西!也许以下内容对您有所帮助你的方式:
#include <stdio.h>
#include <stdlib.h>
#include <errno.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <unistd.h>
int main(
int I__argC,
char *I__argV[]
)
{
int rCode=0;
struct stat statBuf;
FILE *fp = NULL;
char *fileBuf = NULL;
size_t fileBufLength;
char *cp;
/* Verify that caller has supplied I__argV[1], which should be the path
* to the datafile.
*/
if(I__argC != 2)
{
rCode=EINVAL;
fprintf(stderr, "Usage: %s {data file path}\n", I__argV[0]);
goto CLEANUP;
}
/* Get the size of the file (in bytes);
* (assuming that we are not dealing with a sparse file, etc...)
*/
errno=0;
if((-1) == stat(I__argV[1], &statBuf))
{
rCode=errno;
fprintf(stderr, "stat(\"%s\", ...) failed. errno[%d]\n", I__argV[1], errno);
goto CLEANUP;
}
/* Open the caller-specified file in read mode. */
errno = 0;
fp=fopen(I__argV[1], "r");
if(NULL == fp)
{
rCode=errno;
fprintf(stderr, "fopen(\"%s\", \"r\") failed. errno[%d]\n", I__argV[1], errno);
goto CLEANUP;
}
/* Allocate a buffer large enough to hold the entire file content. */
fileBuf=malloc(statBuf.st_size);
if(NULL == fileBuf)
{
rCode=ENOMEM;
fprintf(stderr, "malloc(%zd) failed.\n", statBuf.st_size);
goto CLEANUP;
}
/* Read the file into the fileBuf. */
errno=0;
fileBufLength=fread(fileBuf, 1, statBuf.st_size, fp);
if(fileBufLength != statBuf.st_size)
{
rCode=errno;
fprintf(stderr, "fread() failed to read %zd file bytes. errno[%d]\n",
statBuf.st_size - fileBufLength, errno);
goto CLEANUP;
}
/* Parse the fileBuf for specific data. */
for(cp=fileBuf; cp < fileBuf + fileBufLength; ++cp)
{
long arrivalTime;
long sector;
/* Skip leading white-space (if any) */
if(isspace(*cp))
continue;
/* Parse the 'arrival time'. */
arrivalTime=strtol(cp, &cp, 10);
/* Skip leading white-space (if any) */
while(isspace(*cp))
++cp;
/* Parse the 'sector'. */
sector=strtol(cp, &cp, 10);
printf("%ld, %ld\n", arrivalTime, sector);
}
CLEANUP:
/* Free the fileBuf (if it was successfully allocated) */
if(fileBuf)
free(fileBuf);
/* Close the file (if it was successfully opened) */
if(fp)
fclose(fp);
return(rCode);
}