im trying to do a practice problem from my textbook and im having alot of trouble. Im trying to open files in an range that the user specifies, and doing calculations, moving from file to file. Each file has the following format file05-data-(int 1-99). and the whole file is called practice.exe My main function has the follwing parameters and looks like... say user enters the executable ./practice 10 13
#include <stdio.h>
#include <stdlib.h>
int main(int argc, char* argv[])
{
FILE* newfile;
int i = argc;
while (i<arvf[]) */im pretty sure i<arvf doesnt work but how do i capture
the range inputed by the user,and open each one?*/
{
newfile = fopen(("file05-data-%d.txt",i) "r")
i = i + 1
}
Im confused on how to take the user input, and opening the files in the range that the user inputed. Any help would be appreciated.
E.g
#include <stdio.h>
#include <stdlib.h>
int main(int argc, char* argv[]){
FILE *file;
if(argc != 3){
fprintf(stderr, "Usage >practice start_num end_num\n");
return 1;
}
int start = atoi(argv[1]);
int end = atoi(argv[2]);
if(!(1 <= start && start <= 99 && 1<= end && end <= 99 && start <= end)){
fprintf(stderr, "Specifying the range of values must be 1-99.\n");
return 2;
}
char filename[FILENAME_MAX];
int no;
for(no = start ; no <= end ; ++no){
snprintf(filename, sizeof(filename), "file05-data-%d.txt", no);
if(NULL==(file=fopen(filename, "r"))){
fprintf(stderr, "%s can't open.\n", filename);
//return 3;
continue;
}
/* input && output
char line[128];
while(fgets(line, sizeof(line), file)){
printf("%s", line);
}
*/
fclose(file);
}
return 0;
}
./practice 10 13
This is fine, but your usage of argc and argv is incorrect. I am assuming here that you are trying to open file# 10, 11, 12, 13.
1st put a check whether you are running the binary with right no of inputs (I think you are asking for two arguments) by:
if(argc!=3)
{
// print error msg & exit
}
And to build the file names:
char newfile[MAX_SIZE];
for(i=atoi(argv[1]); i<atoi(argv[2]); i++)
{
snprintf(newfile, "file-data-%d", i);
//open this file, read data, and then loop to the next file
}
That's it!
Related
The wordlist.txt is including like:
able
army
bird
boring
sing
song
And I want to use fscanf() to read this txt file line by line and store them into a string array by indexed every word like this:
src = [able army bird boring sing song]
where src[0]= "able", src[1] = "army" and so on. But my code only outputs src[0] = "a", src[1] = "b"... Could someone help me figure out what's going wrong in my code:
#include <stdio.h>
#include <string.h>
int main(int argc, char *argv[])
{
FILE *fp = fopen("wordlist.txt", "r");
if (fp == NULL)
{
printf("%s", "File open error");
return 0;
}
char src[1000];
for (int i = 0; i < sizeof(src); i++)
{
fscanf(fp, "%[^EOF]", &src[i]);
}
fclose(fp);
printf("%c", src[0]);
getchar();
return 0;
}
Pretty appreciated!
For example like this.
#include <stdio.h>
#include <string.h>
#include <errno.h>
#define MAX_ARRAY_SIZE 1000
#define MAX_STRING_SIZE 100
int main(int argc, char *argv[]) {
FILE *fp = fopen("wordlist.txt", "r");
if (fp == NULL) {
printf("File open error\n");
return 1;
}
char arr[MAX_ARRAY_SIZE][MAX_STRING_SIZE];
int index = 0;
while (1) {
int ret = fscanf(fp, "%s", arr[index]);
if (ret == EOF) break;
++index;
if (index == MAX_ARRAY_SIZE) break;
}
fclose(fp);
for (int i = 0; i < index; ++i) {
printf("%s\n", arr[i]);
}
getchar();
return 0;
}
Some notes:
If there is an error, it is better to return 1 and not 0, for 0 means successful execution.
For a char array, you use a pointer. For a string array, you use a double pointer. A bit tricky to get used to them, but they are handy.
Also, a check of the return value of the fscanf would be great.
For fixed size arrays, it is useful to define the sizes using #define so that it is easier to change later if you use it multiple times in the code.
It's reading file one character at a time, Which itself is 4 in size like we see sizeof('a') in word able. Same goes for 'b' and so on. So one approach you can use is to keep checking when there is a space or newline character so that we can save the data before these two things as a word and then combine these small arrays by adding spaces in between and concatenating them to get a single array.
simple C question here!
So I am trying to parse through a string lets say: 1234567W
#include <stdlib.h>
#include <string.h>
int main(int argc, char *argv[]) {
//pointer to open file
FILE *op;
//open file of first parameter and read it "r"
op = fopen("TestCases.txt", "r");
//make an array of 1000
char x[1000];
char y[1000];
//declare variable nums as integer
int nums;
//if file is not found then exit and give error
if (!op) {
perror("Failed to open file!\n");
exit(1);
}
else {
while (fgets(x, sizeof(x), op)) {
//pounter to get the first coordinate to W
char *p = strtok(x, "W");
//print the first 3 digits of the string
printf("%.4sd\n", p);
}
}
return 0;
My output so far shows: "123d" because of the "%.4sd" in the printf function.
I now need to get the next two numbers, "45". Is there a regex expression I can use that will allow me to get the next two digits of a string?
I am new to C, so I was thinking more like "%(ignore the first 4 characters)(print next 2 digits)(ignore the last two digits)"
input: pic
output: pic
Please let me know.
Thanks all.
printf("Next two: %.2s\n", p + 4); should work.
#include <stdlib.h>
#include <string.h>
#include <stdio.h>
int main(int argc, char *argv[]) {
//pointer to open file
FILE *op;
//open file of first parameter and read it "r"
op = fopen("TestCases.txt", "r");
//make an array of 1000
char x[1000];
char y[1000];
//declare variable nums as integer
int nums;
//if file is not found then exit and give error
if (!op) {
perror("Failed to open file!\n");
exit(1);
}
else {
while (fgets(x, sizeof(x), op)) {
//pounter to get the first coordinate to W
char *p = strtok(x, "W");
//print the first 3 digits of the string
printf("%.4sd\n", p);
printf("Next two: %.2s\n", p + 4);
}
}
return 0;
}
Side note: I added a missing stdio.h include. Please turn on compiler warnings, since this error would've been caught by them.
My program runs correctly, If i manually input any commands it will read everything correctly as well and set it to the correct variables and then output it to a binary file.
But, when I redirect the input file in my command line, it only reads the Command used for the switch, but it does not read anything else in correctly.
for example
a7 < a7Input.txt
Sample of Input Text
r
1023
r
4393
c
3423
Systems Programming
MWF
3
68
c
3421
Systems Programming Recitation
TR
1
68
Enter one of the following actions or press CTRL-D to exit
C - Create a new course record
R - Read an existing course record
U - Update an existing course record
D - Delete an existing course record
This is Choice R
Please Enter a Course Number to Display
courseNumber: 0
courseName: e record
courseSched: urscourseName: 0
courseSize: -1630458206
YOU PICKED C for Create
Please Enter The Details of The Course
Enter a course number:
Enter the course schedule (MWF or TR):
Enter a Course Name:
Enter the course credit hours:
Enter Number of Students Enrolled:
Course Has Been Created!
Notice How it doesn't populate anything from the file, and I'm not entirely sure what is going on if when I manually input stuff, it works correctly.
Here is my code for reference
#include <stdio.h>
#include <string.h>
#include <assert.h>
#include <stdlib.h>
#include <stdarg.h>
typedef struct{
char courseName[64];
char courseSched[4];
unsigned int courseHours;
unsigned int courseSize;
} COURSE;
/* files */
FILE *pfileInputFile;
FILE *pFileDirect;
void proccessInputCommands(char *pszInputFile, char *pszDirectFile, char *argv[]);
void getFileNames(int argc, char *argv[], char **ppszDirectFileName, char **ppszInputTxtFileName);
int main(int argc, char *argv[])
{
char *pszDirectFile = NULL;
char *pszInputFile = NULL;
int rc;
int iCommandType; //Type of command
/* get the filenames and comand type from the command switches */
getFileNames(argc, argv, &pszDirectFile, &pszInputFile);
proccessInputCommands(pszInputFile, pszDirectFile, argv);
return 0;
}
void proccessInputCommands(char *pszInputFile, char *pszDirectFile, char *argv[])
{
COURSE course;
char szInputBuffer[100];
char cCommand;
long lRBA;
long lCourseNum;
char szRemaining[100];
int iScanfCnt;
int iWriteNew;
int rcFseek;
int rc;
// open the txt file for read
pfileInputFile = fopen(pszInputFile, "r");
if(pfileInputFile == NULL)
printf("ERROR\n");
// open the new direct data file for write binary
// if it already exists we simply update it
pFileDirect = fopen(pszDirectFile, "wb+");
if(pFileDirect == NULL)
printf("ERROR\n");
//get commands until EOF
//fgets returns null when EOF is reached
while(fgets(szInputBuffer, 100, pfileInputFile) != NULL)
{
if(szInputBuffer[0] == '\n')
continue;
printf("> %s",szInputBuffer);
iScanfCnt = sscanf(szInputBuffer, "%c\n %ld\n %99[^\n]\n"
, &cCommand
, &lCourseNum
, szRemaining);
if(iScanfCnt < 2)
{
printf("Error: Expected command and Course Number, found: %s\n"
, szInputBuffer);
continue;
}
switch(cCommand)
{
case 'c':
case 'C':
iScanfCnt = sscanf(szRemaining, "%64[^\n] %4s %d %d"
, course.courseName
, course.courseSched
, &course.courseHours
, &course.courseSize);
// check for bad input.
if(iScanfCnt < 4)
printf("ERROR\n");
lRBA = lCourseNum*sizeof(COURSE);
rcFseek = fseek(pFileDirect, lRBA, SEEK_SET);
assert(rcFseek == 0);
// write it to the direct file
iWriteNew = fwrite(&course
, sizeof(COURSE)
, 1L
, pFileDirect);
assert(iWriteNew == 1);
break;
case 'r':
case 'R':
lRBA = lCourseNum*sizeof(COURSE);
rcFseek = fseek(pFileDirect, lRBA, SEEK_SET);
assert(rcFseek == 0);
//print the informatio at the RBA
rc = fread(&course, sizeof(course), 1L, pFileDirect);
if(rc == 1)
printf("%-64s %-4s %5d %5d\n"
, course.courseName
, course.courseSched
, course.courseHours
, course.courseSize);
else
printf("Course Number %ld not found for CBA %ld\n",lCourseNum, lRBA);
break;
default:
printf("unknown command\n");
}
}
//close the file
fclose(pfileInputFile);
fclose(pFileDirect);
}
void getFileNames(int argc, char *argv[], char **ppszDirectFileName, char **ppszInputTxtFileName)
{
int i;
// If there aren't any arguments, show the usage
if (argc <= 1)
printf("No Arguments \n");
// Examine each of the command arguments other than the name of the program.
for (i = 1; i < argc; i++)
{
if(i == 1)
{
*ppszInputTxtFileName = argv[i];
}
if(i == 2)
{
*ppszDirectFileName = argv[i];
}
}
}
So Im trying to print out the first line of a file thats being passed in lets say its a plain text file with a couple of words in the first line.
I open the file and pass it through a function that does some work on the file called process. This little bit of work if for debugging reason , because my ultimate goal is to read in the entire text file line my line and process each line and reverse the words in that line.
But im stuck here i run the program with a text file argument and i get nothing in return and i know my logic sounds right i think? I just want this to ultimately printout every character in that line. Then eventually put all those characters in a char array or char instream[500]
Can someone tell me what iam doing wrong?
#include <stdio.h>
#include <stdlib.h>
void process(FILE *infile);
int main(int argc, char *argv[])
{
int i;
FILE *fp;
printf("argc = %d\n",argc);
for(i = 1 ; i <= argc; i++)
{
fp = fopen(argv[i], "r");
if(fp == NULL)
{
printf("The file: %s doesnt exist.\n", argv[i]);
}
else
{
printf("The file: %s does exist \n",argv[i]);
process(fp);
}
}
return 0;
}
void process(FILE *infile)
{
int k =0;
char iochar;
char instream[500];
while((iochar = getc(infile)) != '\n')
{
printf("Hi there %c", iochar ); // nothing prints out here why not??
//instream[k++] = iochar;
}
}
Working with C.
OK so this is probably something obvious but for some reason my program will only print a certain number of values from a .dat input file as opposed to printing all of them. Here's the code:
#include <stdio.h>
#include <stdlib.h>
int main(int argc, char *argv[])
{
int N = 0;
int j;
float i;
const char Project_Data[] = "FloatValues.dat";
FILE *input = fopen(Project_Data, "r");
if(input != (FILE*) NULL)
{
while(fscanf(input, "%e", &i) == 1)
{
printf("%e\n",i);
++N;
}
printf("\t The number of values in this file is: %d\n", N);
fclose(input);
}
else
printf("Input file could not be read.\n");
return(0);
}
Yeah, so there's about 100000 values or so to be printed yet I only seem to be able to get 20000. The values in the file are ordered sequentially and the compiler only seems to start printing nearer the bottom of the file, after about 80000 or so values.
Anybody know where I'm going wrong?