107_files2.zig 2.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152
  1. //
  2. // Prerequisite :
  3. // - exercise/106_files.zig, or
  4. // - create a file {project_root}/output/zigling.txt
  5. // with content `It's zigling time!`(18 byte total)
  6. //
  7. // Now there's no point in writing to a file if we don't read from it, am I right?
  8. // Let's write a program to read the content of the file that we just created.
  9. //
  10. // I am assuming that you've created the appropriate files for this to work.
  11. //
  12. // Alright, bud, lean in close. Here's the game plan.
  13. // - First, we open the {project_root}/output/ directory
  14. // - Secondly, we open file `zigling.txt` in that directory
  15. // - Then, we initalize an array of characters with all letter 'A', and print it
  16. // - After that, we read the content of the file into the array
  17. // - Finally, we print out the content we just read
  18. const std = @import("std");
  19. pub fn main() !void {
  20. // Get the current working directory
  21. const cwd = std.fs.cwd();
  22. // try to open ./output assuming you did your 106_files exercise
  23. var output_dir = try cwd.openDir("output", .{});
  24. defer output_dir.close();
  25. // try to open the file
  26. const file = try output_dir.openFile("zigling.txt", .{});
  27. defer file.close();
  28. // initalize an array of u8 with all letter 'A'
  29. // we need to pick the size of the array, 64 seems like a good number
  30. // fix the initalization below
  31. var content = ['A']*64;
  32. // this should print out : `AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA`
  33. std.debug.print("{s}\n", .{content});
  34. // okay, seems like a threat of violence is not the answer in this case
  35. // can you go here to find a way to read the content?
  36. // https://ziglang.org/documentation/master/std/#std.fs.File
  37. // hint: you might find two answers that are both valid in this case
  38. const bytes_read = zig_read_the_file_or_i_will_fight_you(&content);
  39. // Woah, too screamy. I know you're excited for zigling time but tone it down a bit.
  40. // Can you print only what we read from the file?
  41. std.debug.print("Successfully Read {d} bytes: {s}\n", .{
  42. bytes_read,
  43. content, // change this line only
  44. });
  45. }