gpt4 book ai didi

c - 理解这个 shell 脚本分配

转载 作者:行者123 更新时间:2023-12-04 19:00:04 25 4
gpt4 key购买 nike

我需要一些帮助来理解这个 Linux 编程任务。
我必须使用这个 C 程序来随机化一个文本文件,这里是程序:

//
// shuffle.c
// Filter that reads every line from stdin (or a specified file),
// shuffles them randomly, and outputs the shuffled lines to stdout.
// This is a partial replacement for the 'shuf' command provided
// with most Linux installations.
// Author: W. Cochran wcochran@wsu.edu
//

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

//
// Seed stdlib's random() with a random
// seed using kernel urandom device.
//
void seedRandom(void) {
FILE *f;
if ((f = fopen("/dev/urandom", "rb")) == NULL) {
perror("/dev/urandom");
exit(-1);
}
unsigned int seed;
fread(&seed, sizeof(seed), 1, f);
fclose(f);
srandom(seed);
}

//
// Fisher–Yates shuffle using stdlib's random()
// https://en.wikipedia.org/wiki/Fisher–Yates_shuffle#Potential_sources_of_bias
// Not really doing this exactly right, see
// https://channel9.msdn.com/Events/GoingNative/2013/rand-Considered-Harmful
//
void shuffle(int numLines, char *lines[]) {
for (int i = 0; i < numLines-1; i++) {
const int n = numLines - i;
const int j = random() % n + i;
char *tmp = lines[i];
lines[i] = lines[j];
lines[j] = tmp;
}
}

int main(int argc, char *argv[]) {
//
// Read from stdin by default else read from
// first argument specified on command line.
//
FILE *f = stdin;
if (argc >= 2) {
f = fopen(argv[1], "rb");
if (f == NULL) {
perror(argv[1]);
exit(1);
}
}

//
// Buffer each input line into (dynamically sized) array.
// Caveat: Assume lines are less than 200 chars long (I'm too
// lazy to do this right).
//
int capacity = 10;
int numLines = 0;
char **lines = (char **) malloc(capacity * sizeof(char *));
char buf[200];
while (fgets(buf, sizeof(buf), f) != NULL) {
if (numLines >= capacity) {
capacity *= 2;
lines = realloc(lines, capacity * sizeof(char *));
}
lines[numLines++] = strdup(buf);
}

fclose(f);

//
// Seed random number generator used by shuffle.
//
seedRandom();

//
// Shuffle lines.
//
shuffle(numLines, lines);

//
// Echo shuffled lines to stdout.
//
for (int i = 0; i < numLines; i++)
printf("%s", lines[i]);

return 0;
}

作业告诉我以下内容:

so I can't copy and paste because the pdf is troublesome but I have included a screenshot I hope you can find it.

我只是需要帮助来解决这一点,拜托。

如何使用 shuffle一旦我编译它?使用我提供的屏幕截图中刚刚提供的代码有什么意义?

最佳答案

该脚本代码块设置变量 SHUF到您应该用来随机播放文件的程序。要么是系统的shuf程序或您老师的shuffle程序。

代码完成后,可以使用$SHUF运行找到的任何程序。

$SHUF filename.txt

关于c - 理解这个 shell 脚本分配,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60536668/

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